-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile-picker.ts
48 lines (38 loc) · 1.16 KB
/
file-picker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
export type FilePickerConfigs = {
multiple?: boolean
accept?: string
}
/**
* web file picker
* @param configs picker configs
* @param configs.multiple if you want to take multiple files
* @param configs.accept if you want limit to specific file types
* @returns list of selected files
*/
export async function filePicker(configs?: FilePickerConfigs): Promise<globalThis.File[] | null> {
let closeWithoutSelectAnyFile = true
const fileInput = document.createElement('input')
fileInput.hidden = true
fileInput.type = 'file'
fileInput.multiple = configs?.multiple || false
fileInput.accept = configs?.accept || '*/*'
return await new Promise(resolve => {
window.onfocus = () => {
setTimeout(() => {
if (closeWithoutSelectAnyFile) {
resolve(null)
}
}, 300)
}
fileInput.onchange = e => {
closeWithoutSelectAnyFile = false
const files = (e.target as any).files as globalThis.FileList
const fileList: File[] = []
for (let fileIndex = 0; fileIndex < files.length; fileIndex++) {
fileList.push(files[fileIndex])
}
resolve(fileList)
}
fileInput.click()
})
}