Last active
October 18, 2024 14:43
-
-
Save mastermakrela/8a04c0633dadee1279c423387f8f5a63 to your computer and use it in GitHub Desktop.
File selector for js/ts
This file contains hidden or 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
export async function open_file({ accept }: { accept?: string }): Promise<File> { | |
const input = document.createElement('input'); | |
input.type = 'file'; | |
if (accept) input.accept = accept; | |
input.click(); | |
return new Promise((resolve, reject) => { | |
input.onchange = () => { | |
const file_handle = input.files?.[0]; | |
if (file_handle) { | |
resolve(file_handle); | |
} else { | |
reject(new Error('No file selected')); | |
} | |
input.remove(); | |
}; | |
}); | |
} | |
export async function save_file( | |
content: Blob | string, | |
filename: string, | |
options?: { type?: string } | |
): Promise<void> { | |
const blob = content instanceof Blob ? content : new Blob([content], options); | |
const url = URL.createObjectURL(blob); | |
const a = document.createElement('a'); | |
a.href = url; | |
a.download = filename; | |
// Append the anchor to the body (required for Firefox) | |
document.body.appendChild(a); | |
a.click(); | |
// Clean up | |
setTimeout(() => { | |
document.body.removeChild(a); | |
URL.revokeObjectURL(url); | |
}, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment