Created
February 6, 2023 14:22
-
-
Save westc/89d536e92d7adf5dc859d3c9eed8a9cc to your computer and use it in GitHub Desktop.
Provides selectFile() and selectFiles() to be able to select one or more files on a webpage.
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
function getSelectFiles(multiple) { | |
/** | |
* @param {selectFile_Options} options | |
*/ | |
function f(options) { | |
options = Object(options); | |
const input = Object.assign(document.createElement('input'), { | |
type: 'file', | |
multiple, | |
onchange: () => options.callback(input.files), | |
}); | |
if (options.accept) { | |
input.accept = Array.isArray(options.accept) | |
? options.accept.join(',') | |
: options.accept; | |
} | |
if (options.capture) input.capture = options.capture; | |
input.click(); | |
} | |
/** | |
* @typedef {Object} selectFile_Options | |
* @property {(fileList: FileList) => void} callback | |
* The function that is called after 1 or more files are selected. Will not | |
* be called if the user clicks cancel. | |
* @property {string|string[]} accept | |
* Optional. Defines the file types to accept. | |
* @property {string} capture | |
* Optional. Specifies which camera to use for capture of image or video data, | |
* if the `accept` attribute indicates the input should be of one of those | |
* types. A value of `"user"` indicates that the user-facing camera and/or | |
* microphone should be used. A value of `"environment"` specifies that the | |
* outward-facing camera and/or microphone should be used. If this attribute | |
* is missing, the user agent is free to decide on its own what to do. If the | |
* requested facing mode isn't available, the user agent may fall back to its | |
* preferred default mode. | |
*/ | |
return f; | |
} | |
const selectFile = getSelectFiles(false), selectFiles = getSelectFiles(true); |
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
selectFile({ | |
callback(fileList) { | |
console.log(fileList); | |
}, | |
accept: ['.css', '.js'], | |
}); | |
selectFiles({ | |
callback(fileList) { | |
console.log(fileList); | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment