Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Set the FileList of <input type="file"> to arbitrary File objects
<!DOCTYPE html>
<!-- guest271314 11-12-2017 -->
<!-- see -->
const input = document.createElement("input");
const label = document.createElement("label");
const text = document.createTextNode("click to set files\n");
const form = document.createElement("form");
const data = [
new File(["a"], "a.txt"), new File(["b"], "b.txt")
class _DataTransfer {
constructor() {
return new ClipboardEvent("").clipboardData || new DataTransfer();
input.type = "file"; = "files[]";
input.multiple = true; = "files";
text.textContent = text.textContent.concat({
}) => name).join(", "), "\n");
label.onclick = e => {
const dt = new _DataTransfer();
for (let file of data) {
if (dt.files.length) {
input.files = dt.files; // set `FileList` of `dt.files`: `DataTransfer.files` to `input.files`
for (const file of input.files) {
console.log(file); // `File` objects originally set at `data`, set at `input.files`
const fd = new FormData(form); // pass `form` to `fd`: `FormData`
for (const [key, prop] of fd) {
console.log(key, prop); // `File` objects set at `fd`
// not dispatched at Firefox 57 when set using `input.files = dt.files`
input.onchange = e => {
console.log(e, input.files);

This comment has been minimized.

Copy link

Kaiido commented Dec 4, 2017

For Firefox, I believe this is a bug in their implementation of the ClipboardEvent constructor, I am not sure they should let the items property accessible, if I read the specs right, it should be set to null, when no ClipboardEventInit parameter is passed, but I have to admit I don't really understand how this syntax should be read, since the very next example seems to imply that their implementation is the correct one.

But anyway, you are right that the DataTransfer constructor in its current specifications does allow to set arbitrary data to a FileList from scratch... (only chrome does support this constructor at the moment).

I am not sure if this was intended though...


This comment has been minimized.

Copy link

Kaiido commented Dec 5, 2017

Your discovery lead to this proposal: whatwg/html#3269 (comment)
I will also edit the StackOverflow answer giving you credits, you will probably be able to self-answer after your account ban turns-off.


This comment has been minimized.

Copy link
Owner Author

guest271314 commented Dec 6, 2017

@Kaiido ClipboardEvent was used for Firefox, DataTransfer was used for Chromium, to achieve same result at each browser. Did not read the ClipboardEvent specification before trying different approaches.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.