budibase/packages/frontend-core/src/utils/download.js

67 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-04-10 15:15:24 +02:00
const extractFileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
export function downloadText(filename, text) {
if (typeof text === "object") {
text = JSON.stringify(text)
}
const blob = new Blob([text], { type: "plain/text" })
const url = URL.createObjectURL(blob)
const link = document.createElement("a")
link.href = url
link.download = filename
link.click()
URL.revokeObjectURL(url)
}
2023-07-10 13:25:24 +02:00
2023-07-10 13:57:27 +02:00
export async function downloadStream(streamResponse) {
2023-07-10 13:25:24 +02:00
const blob = await streamResponse.blob()
2023-07-10 13:57:27 +02:00
const contentDisposition = streamResponse.headers.get("Content-Disposition")
2024-04-10 15:15:24 +02:00
const matches = extractFileNameRegex.exec(contentDisposition)
2023-07-10 13:57:27 +02:00
const filename = matches[1].replace(/['"]/g, "")
2023-07-10 13:25:24 +02:00
const resBlob = new Blob([blob])
const blobUrl = URL.createObjectURL(resBlob)
const link = document.createElement("a")
link.href = blobUrl
link.download = filename
link.click()
URL.revokeObjectURL(blobUrl)
}
2024-03-22 11:34:05 +01:00
export async function downloadFile(url, body) {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
})
if (!response.ok) {
return false
2024-03-25 10:24:20 +01:00
} else {
const contentDisposition = response.headers.get("Content-Disposition")
2024-03-22 11:34:05 +01:00
2024-04-10 15:15:24 +02:00
const matches = extractFileNameRegex.exec(contentDisposition)
2024-03-22 11:34:05 +01:00
2024-03-25 10:24:20 +01:00
const filename = matches[1].replace(/['"]/g, "")
2024-03-22 11:34:05 +01:00
2024-03-25 10:24:20 +01:00
const url = URL.createObjectURL(await response.blob())
2024-03-22 11:34:05 +01:00
2024-03-25 10:24:20 +01:00
const link = document.createElement("a")
link.href = url
link.download = filename
link.click()
2024-03-25 10:24:20 +01:00
URL.revokeObjectURL(url)
return true
}
2024-03-22 11:34:05 +01:00
}