davidtgq
davidtgq

Reputation: 4000

How to work with FileList (from <input type="file">) in Javascript?

In this W3schools example, console.log on the input element reveals a FileInput object:

FileList {0: File, 1: File, length: 2}

How can I work with this? The example demonstrates accessing the file, but every time a user selects new files, the old files disappear. How can I create a new empty FileList and copy it over, so that a user can add more files to the FileList?

I tried this, but it results in two FileList objects, rather than one FileList with all the files:

var fileStore = x.files;

function myFunction(){
    var txt = "";
    if ('files' in x) {
        if (x.files.length == 0) {
            txt = "Select one or more files.";
        } else {
            fileStore += x.files;
            console.log(x.files);
            console.log(fileStore);

Upvotes: 10

Views: 64495

Answers (4)

Enmanuel López
Enmanuel López

Reputation: 81

it is possible to add files using the datatransfer class

export const makeFileList = files => {
  const reducer = (dataTransfer, file) => {
    dataTransfer.items.add(file);
    return dataTransfer;
  }

  return files.reduce(reducer, new DataTransfer()).files;
}

Upvotes: 8

james_womack
james_womack

Reputation: 10296

An array is fine for holding onto the File instances, but FormData is better if you want to upload them somewhere. If you want to log out or view the FormData, turning it into a Map is an option. Keep in mind that FormData is iterable.

var formData = new FormData();
var index = 0;

function onDrop(event)
{
  var dt = event.dataTransfer;
  var files = dt.files;

  var count = files.length;
  output("File Count: " + count + "\n");

  for (var i = 0; i < files.length; i++) {    
    formData.append(files[i].name, files[i]);
  }
}

function output(text)
{
  document.getElementById("output").textContent += text;
  console.dir(new Map(formData));
}

See this JSBin.

Upvotes: 6

guest271314
guest271314

Reputation: 1

It is not possible to add File objects to FileList. You can use FormData to append Files to a single object.

var data = new FormData();
document.querySelector("input[type=file]")
.addEventListener("change", function(event) {
  for (var i = 0, files = event.target.files; i < files.length; i++) {
    data.append("file-" + [...data.keys()].length, files[i], files[i].name)
  }
})

Upvotes: 6

Isaac
Isaac

Reputation: 11805

Untested, but this should work

var fileStore = [];

function myFunction(){
    var txt = "";
    if ('files' in x) {
        if (x.files.length == 0) {
            txt = "Select one or more files.";
        } else {
            fileStore.push.apply(fileStore,x.files);
            console.log(x.files);
            console.log(fileStore);

More on Function::apply

More on Array::push

Upvotes: 10

Related Questions