|
| 1 | +export const makeFileList = (myFileArray) => { |
| 2 | + return new Promise((resolve, reject) => { |
| 3 | + const input = document.createElement("input"); |
| 4 | + input.style.display="none"; |
| 5 | + const label = document.createElement("label"); |
| 6 | + label.style.display="none"; |
| 7 | + const text = document.createTextNode("click to set files\n"); |
| 8 | + const form = document.createElement("form"); |
| 9 | + const data = myFileArray; |
| 10 | + // https://github.com/w3c/clipboard-apis/issues/33 |
| 11 | + class _DataTransfer { |
| 12 | + constructor() { |
| 13 | + return new ClipboardEvent("").clipboardData || new DataTransfer(); |
| 14 | + } |
| 15 | + } |
| 16 | + input.type = "file"; |
| 17 | + input.name = "files[]"; |
| 18 | + input.multiple = true; |
| 19 | + input.id = "files"; |
| 20 | + text.textContent = text.textContent.concat( |
| 21 | + data.map(({ name }) => name).join(", "), |
| 22 | + "\n" |
| 23 | + ); |
| 24 | + |
| 25 | + label.appendChild(text); |
| 26 | + form.appendChild(label); |
| 27 | + form.appendChild(input); |
| 28 | + document.body.appendChild(form); |
| 29 | + // https://github.com/whatwg/html/issues/3222 |
| 30 | + // https://bugzilla.mozilla.org/show_bug.cgi?id=1416488 |
| 31 | + label.onclick = (e) => { |
| 32 | + const dt = new _DataTransfer(); |
| 33 | + for (let file of data) { |
| 34 | + dt.items.add(file); |
| 35 | + } |
| 36 | + if (dt.files.length) { |
| 37 | + input.files = dt.files; |
| 38 | + } |
| 39 | + const fd = new FormData(form); |
| 40 | + for (const file of input.files) { |
| 41 | + //console.log(file); // `File` objects set at `data` |
| 42 | + } |
| 43 | + for (const [key, prop] of fd) { |
| 44 | + // console.log(key, prop); |
| 45 | + } |
| 46 | + //console.log(input.files); |
| 47 | + resolve(input.files); |
| 48 | + }; |
| 49 | + // not dispatched at Firefox 57 when set using `input.files = dt.files` |
| 50 | + input.onchange = (e) => { |
| 51 | + console.log("onchange", e, input.files); |
| 52 | + //resolve("onchange", input.files); |
| 53 | + }; |
| 54 | + label.click(); |
| 55 | + }); |
| 56 | +}; |
0 commit comments