سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top