Get the files chosen using the input type file 

2019-02-14 20:16发布

问题:

In my HTML i select multiple files.

<input type="file" id="img" multiple>

I want to store each element in an array so that i can print the file source.

I have done this in my javascript but it does not work.

function loadfiles()
{
var x=document.getElementById("img");
for (var i=0;i<x.length;i++)
{
  document.write(x.elements[i].src);
}
}

回答1:

The property files gets you an array of all the files selected by the file input. So the loadfiles function should be modified to following:

function loadfiles()
{
    var imageFiles = document.getElementById("img"),
    filesLength = imageFiles.files.length;
    for (var i = 0; i < filesLength; i++) {
      document.write(imageFiles.files[i].name);
    }
}


回答2:

DOM documentation (Mozilla):

element = document.getElementById(id);

where

  • element is a reference to an Element object, or null if an element with the specified ID is not in the document.
  • id is a case-sensitive string representing the unique ID of the element being sought.

In your code document.getElementById(id) returns a single element and not a list.
To access the files added to the input take a look at the HTML5 Files API.

var f = (document.getElementById('img').files);
for (var i =0; i < f.length; i++){
   var new_div = document.createElement('div');
   new_div.innerHTML = f[i].name;
   document.body.appendChild(new_div);   
}

FYI: Using document.write() is extremely dangerous, and should be avoided. For more read this stackoverflow Q&A: Why is document.write considered a "bad practice"?

In the example above I substituted document.write with document.body.appendChild

Fiddle (with jQuery): http://jsfiddle.net/4Yq4F/

Getting the complete file path

This is in your response requesting for the complete file path of the files. Unfortunately due to security reasons this is not possible as of now. Mozilla Firefox browsers however will provide you with the complete file path with the mozFullPath attribute. If you want to use it, in the above example substitute f[i].name with f[i].mozFullPath



回答3:

This should work for you...

function loadfiles()
{
    var x=document.getElementsByTagName("input");
    for (var i=0;i<x.length;i++)
    {
         if(x[i].type == "file"){
             document.write(x[i].value);
         }
     }
}


回答4:

this code will be work for you.

HTML

<input type="text" id="text"/>
<input type="button" value="add" id="adda"/>

JavaScript

var arry=[];
$("#adda").click(function(){
   arry.push( $("#text").val());
    alert(arry);
});


回答5:

var fileArray = new Array();
 $('#inputPostFile').change(function() {
                var files = this.files;
                   $('.uploadedFileList').html('');
                $.each(files, function (index, value) {
                    fileArray.push(value);
                });
            });