Skip to content

Instantly share code, notes, and snippets.

@msulais
Last active October 5, 2024 14:01
Show Gist options
  • Save msulais/29451d25396a922b3ec24856a8cca521 to your computer and use it in GitHub Desktop.
Save msulais/29451d25396a922b3ec24856a8cca521 to your computer and use it in GitHub Desktop.
Open file in Typescript without <input type=file>
async function openFile(
accept: string | null, // file type (see https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/accept)
multiple: boolean = false,
capture?: string | null // see https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/capture
): Promise<FileList | null> {
return new Promise<FileList | null>((ok) => {
const filePickerRef = document.createElement('input')
filePickerRef.type = 'file'
if (accept != null) filePickerRef.accept = accept
if (capture != null) filePickerRef.capture = capture
filePickerRef.multiple = multiple
filePickerRef.click()
filePickerRef.onchange = () => {
ok(filePickerRef.files)
filePickerRef.remove()
}
filePickerRef.oncancel = () => {
ok(null)
filePickerRef.remove()
}
})
}
// example to get image file (PNG, JPEG, GIF, SVG, etc)
openFile('image/*', true).then(files => {
if (files == null || files.length == 0) return;
// TODO: do something with the files here
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment