0

I try to upload single files and stack them in the same array but every time I do it, Its create a new array with same name , I like to be every time you add new file to record in this array so on submit to submit them all

<input type="file" name="file-input" multiple id="file-upload"/>

Jquery

  var fileInput = document.getElementById('file-upload');
  var fileList = [];
  fileInput.addEventListener('change', function (event)
  {
      for (var i = 0; i < this.files.length; i++)
      fileList.push(fileInput.files[i]);
    {
      console.log(fileInput.files)
    }
  });
3
  • Your file input does not have the multiple attribute set, so it can only “hold”/ select one single file at a time. So your for loop will run only one time each time you select a file as well. Not sure what you mean by “it open a new array” though. Commented Aug 23, 2018 at 10:58
  • Why not just use <input type="file" multiple="true" />? Then you get this exact behaviour by default, without need for JS Commented Aug 23, 2018 at 11:05
  • sorry i forget to add attribute multiple in the post i want each time you select/change/add file to stack in same array so if you add 10 single files in one array than u can submit them all by default each time you select new file old one is deleted Commented Aug 23, 2018 at 12:41

1 Answer 1

3

The problem is this line:

<input type="file" name="file-input" id="file-upload"/>.

You have to add multiple so that it can add more than one images.

<input type="file" name="file-input" id="file-upload" multiple/>

Also, for loop looks wrong with the brackets.

 var fileList = [];

 var fileInput = document.getElementById('file-upload');

 fileInput.addEventListener('change', function (event)
 {

 for (var i = 0; i < fileInput.length; i++)
 {
  fileList.push($('#file-upload')[0].files[i]);
 }

  console.log(fileList);

});
Sign up to request clarification or add additional context in comments.

5 Comments

It's probably best to redefine fileList as an empty array inside the change event too so that it's an exact replication of the file control
yes i add attribute multiple on input but what about fileList an empty ? i try it var var fileList = Array(); but still on every change to create new array with this name isnt record changes in the exist array
What are you trying to achieve? Submit the form?
im trying each time you add file to stack in array and when you submit the form to submit all files you have been added , if i select 2-3 files together is working fine but when i select them one buy one they dont stack in array and submit only last file added
Updated Answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.