-
Notifications
You must be signed in to change notification settings - Fork 5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
19 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,24 @@ | ||
import { getRandomFileName } from './util'; | ||
|
||
function encodeB64(text, cb) { | ||
const buf = new TextEncoder().encode(text); | ||
// eslint-disable-next-line no-undef | ||
const reader = new FileReader(); | ||
reader.onload = () => cb(reader.result.split(',')[1]); | ||
// eslint-disable-next-line no-undef | ||
reader.readAsDataURL(new Blob([buf])); | ||
function encodeB64(text) { | ||
return new Promise((resolve) => { | ||
const buf = new TextEncoder().encode(text); | ||
// eslint-disable-next-line no-undef | ||
const reader = new FileReader(); | ||
reader.onload = () => resolve(reader.result.split(',')[1]); | ||
// eslint-disable-next-line no-undef | ||
reader.readAsDataURL(new Blob([buf])); | ||
}); | ||
} | ||
|
||
export function exportAsFile(filename, data, type = 'text/csv') { | ||
encodeB64(data, (b64) => { | ||
// eslint-disable-next-line no-param-reassign | ||
filename = filename || getRandomFileName(); | ||
const elem = window.document.createElement('a'); | ||
elem.href = `data:${type};Base64,${b64}`; | ||
elem.download = filename; | ||
document.body.appendChild(elem); | ||
elem.click(); | ||
document.body.removeChild(elem); | ||
}); | ||
export async function exportAsFile(filename, data, type = 'text/csv') { | ||
const b64 = await encodeB64(data); | ||
// eslint-disable-next-line no-param-reassign | ||
filename = filename || getRandomFileName(); | ||
const elem = window.document.createElement('a'); | ||
elem.href = `data:${type};Base64,${b64}`; | ||
elem.download = filename; | ||
document.body.appendChild(elem); | ||
elem.click(); | ||
document.body.removeChild(elem); | ||
} |