Skip to content

Instantly share code, notes, and snippets.

@theabbie
Created December 24, 2020 16:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theabbie/836394d1b4167c1c5deb407c16a6e871 to your computer and use it in GitHub Desktop.
Save theabbie/836394d1b4167c1c5deb407c16a6e871 to your computer and use it in GitHub Desktop.
Promise-based File Picker in Javascript
// 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
Copy link

CongAn commented Dec 8, 2022

There is no reject, and the cancellation will wait indefinitely。

@theabbie
Copy link
Author

theabbie commented Dec 8, 2022

@CongAn yeah, that's a bug, will fix

@CongAn
Copy link

CongAn commented Dec 8, 2022

@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 })

@theabbie
Copy link
Author

theabbie commented Dec 8, 2022

@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