Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 855
davidtgq Avatar asked Jul 26 '16 02:07

davidtgq


People also ask

How do I use FileList?

Just type the word Filelist.exe followed by the full path of the directory that you want to scan. This command creates a list of the files that are located in the Music directory.

How do you assign a value to an input type file?

In HTML, we will use the type attribute to take input in a form and when we have to take the file as an input, the file value of the type attribute allows us to define an element for the file uploads.

How do you read a file in Javascript?

To read a file, use FileReader , which enables you to read the content of a File object into memory. You can instruct FileReader to read a file as an array buffer, a data URL, or text. // Check if the file is an image.

Is FileList an array?

FileList is an object which represents an array of individually selected files from the underlying system.


2 Answers

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

like image 178
Isaac Avatar answered Nov 03 '22 01:11

Isaac


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)
  }
})
like image 29
guest271314 Avatar answered Nov 03 '22 00:11

guest271314