-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile-picker.js
45 lines (38 loc) · 1.14 KB
/
file-picker.js
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
/**
* web file picker
* @param {Object} configs picker configs
* @param {boolean} [configs.multiple=] if you want to take multiple files
* @param {string} [configs.accept=] if you want limit to specific file types
* @returns {Promise<globalThis.File[]>} list of selected files
*/
export async function filePicker(configs) {
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([]);
}
}, 300);
};
fileInput.onchange = (e) => {
closeWithoutSelectAnyFile = false;
const files = e.target.files;
if (files) {
resolve(files);
} else {
const fileList = [];
for (let fileIndex = 0; fileIndex < files.length; fileIndex++) {
fileList.push(files[fileIndex]);
}
resolve(fileList);
}
};
fileInput.click();
});
}