@cmk/fe_utils
Version:
frontend utility library
37 lines (33 loc) • 1.13 kB
text/typescript
export function createAndDownloadFileWithText(filename: string, text: string) {
const element = document.createElement('a')
element.setAttribute(
'href',
'data:text/plain;charset=utf-8,' + encodeURIComponent(text)
)
element.setAttribute('download', filename)
element.style.display = 'none'
document.body.appendChild(element)
element.click()
document.body.removeChild(element)
}
export const toBase64 = (file: File) =>
new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => resolve(reader.result)
reader.onerror = reject
})
export const labeledBase64PdfToPureBase64File = (
labeledBase64: string
): string => labeledBase64.replace(/data:image\/.*;base64,/, '')
export function dataURLtoFile(dataurl: string, filename: string): File {
const arr = dataurl.split(',')
const mime = arr?.[0]?.match?.(/:(.*?);/)?.[1]
const bstr = atob(arr[arr.length - 1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], filename, { type: mime })
}