Get the files selected using the input type file (several) and save them in an array

In my HTML, I select multiple files.

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

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

I did 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); } } 
+4
source share
5 answers

The files property gets an array of all files selected by file input. Therefore, the loadfiles function should be changed as follows:

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

DOM Documentation (Mozilla):

element = document.getElementById(id);

Where

  • element is a reference to an Element or null if the element with the specified identifier is not in the document.
  • id is a string string representing the unique identifier of the item being searched.

In your code, document.getElementById(id) returns one element, not a list.
To access the files added to the input, check out the HTML5 file 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() extremely dangerous and should be avoided. To learn more about this stackoverflow method. Q & A: Why is document.write considered "bad practice"?

In the above example, I replaced document.write with document.body.appendChild

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

Getting the full path to the file

This is the answer in your request for the full file path. Unfortunately, due to security concerns, this is not at the moment. However, Mozilla Firefox will provide you with the full path to the file with the mozFullPath attribute. If you want to use it, in the example above replace f[i].name with f[i].mozFullPath

+2
source

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); } } } 
+1
source

this code will 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); }); 
0
source
 var fileArray = new Array(); $('#inputPostFile').change(function() { var files = this.files; $('.uploadedFileList').html(''); $.each(files, function (index, value) { fileArray.push(value); }); }); 
0
source

Source: https://habr.com/ru/post/1489044/


All Articles