Created
December 24, 2020 16:24
-
-
Save theabbie/836394d1b4167c1c5deb407c16a6e871 to your computer and use it in GitHub Desktop.
Promise-based File Picker in Javascript
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
// opens file dialog waits till user selects file and return dataurl of uploaded file | |
async function pick() { | |
var filepicker = document.createElement("input"); | |
filepicker.setAttribute("type","file"); | |
filepicker.click(); | |
return new Promise((resolve,reject) => { | |
filepicker.addEventListener("change", e => { | |
var reader = new FileReader(); | |
reader.addEventListener('load', file => resolve(file.target.result)); | |
reader.readAsDataURL(e.target.files[0]); | |
}); | |
}); | |
} | |
// Only call this function on a user event | |
window.onclick = async function() { | |
var file = await pick(); | |
console.log(file); | |
} |
@CongAn yeah, that's a bug, will fix
@CongAn yeah, that's a bug, will fix
I found an answer. Maybe I can add the following code to solve it, but in fact, there is no way to know whether the user has clicked the Cancel button.
// ……
filepicker.addEventListener('change', () => {
// ……
filepicker = undefined
})
// ……
window.addEventListener('focus', () => {
setTimeout(() => {
if (filepicker) {
filepicker= undefined
reject(new Error('File deselected!'))
}
}, 300)
}, { once: true })
@CongAn oh, that's a good solution, thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is no reject, and the cancellation will wait indefinitely。