Last active
October 5, 2024 14:01
-
-
Save msulais/29451d25396a922b3ec24856a8cca521 to your computer and use it in GitHub Desktop.
Open file in Typescript without <input type=file>
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
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