Javascript: understanding the File interface

I start with Javascript and try to understand some basics. The questions concern not only the File interface, but also 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 the file type is File .

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

In W3, an API is defined as:

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

I am trying to figure out how I can access a single file in a FileList using files . It seems to be undefined anywhere. Where does the files array come from?

+6
source share
1 answer

The files property returns a FileList .

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

To access individual files, you can simply iterate over them, like any other List / Array. For instance:.

 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 +" name = " + files[i].name + '; size: ' + files[i].size + ' bytes'); } 

Demo

MDN has a good tutorial for using API files .

+5
source

All Articles