Skip to content

Instantly share code, notes, and snippets.

@westc
Last active November 27, 2024 01:38
Show Gist options
  • Save westc/b86c0202d3b4acbf2ccb3276835afe4e to your computer and use it in GitHub Desktop.
Save westc/b86c0202d3b4acbf2ccb3276835afe4e to your computer and use it in GitHub Desktop.
selectFile() - Shows the file selector dialog and returns an array of the selected files.
/**
* Shows the file selector dialog and returns an array of the selected files.
* @param {?selectFile__Options=} options
* @returns {Promise<File[]>}
*/
function selectFile(options) {
return new Promise(resolve => {
function onClose(e) {
resolve([...e.target.files]);
}
Object.assign(document.createElement('input'), {
type: 'file',
accept: options?.accept?.join(', '),
multiple: options?.multiple ?? false,
onchange: onClose,
oncancel: onClose,
}).click();
});
}
/**
* @typedef selectFile__Options
* @property {?string[]=} accept
* Optional array of acceptable file types (e.g., ['.jpg', '.png']).
* @property {?boolean=} multiple
* Defaults to `false`. Whether to allow selecting multiple files.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment