Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Created July 30, 2020 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmccray/4ec336332cd094a8af2c3392a23cb424 to your computer and use it in GitHub Desktop.
Save mattmccray/4ec336332cd094a8af2c3392a23cb424 to your computer and use it in GitHub Desktop.
export function selectImage(accepts: string = "image/*"): Promise<File | null> {
return new Promise((resolve, reject) => {
const input = createFileInput(accepts)
let focusCount = 0
let fileWasSelected = false
input.onchange = (e: any) => {
fileWasSelected = true
const file = e.target.files[0]
resolve(file)
}
input.onfocus = (e: any) => {
if (focusCount > 0) { // Second focus happens after the system file picker is closed
setTimeout(() => {
if (!fileWasSelected) {
resolve(null)
}
//console.log("(REMOVING INPUT)")
input.onchange = input.onfocus = null
document.body.removeChild(input)
}, 200)
}
focusCount += 1
}
//console.log("(ADDING INPUT)")
document.body.appendChild(input)
input.focus()
input.click()
})
}
function createFileInput(accepts?: string) {
const input = document.createElement("input")
input.type = "file"
input.accept = accepts
input.style.position = "absolute"
input.style.top = "0px"
input.style.left = "0px"
input.style.opacity = "0"
input.style.pointerEvents = 'none'
return input
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment