Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Understanding File interface

I'm getting started with Javascript and trying to understand some fundamentals. The questions is not specifically about File interface, but it is what I'm trying to figure out.

In my HTML file I have a file type input.

<input type="file" id="fileInput" multiple/>

Then in my JS file I have:

var fileVar = document.getElementById('fileInput').files[0];

This works fine and filevar is of type File.

Now I'm trying to understand how files attribute works.

In W3 the API is defined as:

 interface FileList {
      getter File? item(unsigned long index);
      readonly attribute unsigned long length;
    };

I'm trying to figure out how I can access the individual File's in FileList by using files. It doesn't seem to be defined anywhere. Where is the array files coming from?

like image 594
madu Avatar asked Feb 26 '13 14:02

madu


1 Answers

The files property returns a FileList.

files is a property of the HTMLInputElement Interface, that is, the DOM interface for <input> tags. It is implemented by browsers that support the HTML5 File API.

To access individual files you can just iterate over them like any other List/Array. E.g.:

var files = element.files; //where `element` is a file input element reference
//`files` references a FileList, you can iterate over it and access its File objects
for (var i = 0; i < files.length; i++) {
    console.log('File '+ i +"'s name = " + files[i].name +
        '; size: ' + files[i].size + ' bytes');
}

Demo

MDN has a nice tutorial for using the File API as well.

like image 74
Fabrício Matté Avatar answered Sep 28 '22 00:09

Fabrício Matté