Assign multiple images (files) from one file input

2019-01-29 13:02发布

问题:

I have successful upload code that works perfect using the AJAX when I select each file to upload from the dialog. So each upload has its own form and input file (button to upload) as seen below. The current code uploads files sequentially as the user can select more than one photo but not together & I use queuing algorithm with setTimeout in Javascript to check if the first upload finishes to start the second upload, third, and so on.

<form id="form1">
    <input type="file" id="userfile1" name="userfile[]" multiple/>
</form>

<form id="form2">
    <input type="file" id="userfile2" name="userfile[]" multiple/>
</form>
.
.
.

The problem now, when I select multiple images to upload (let's say two images together using Ctrl), using the first input file, I get them in this array:

document.getElementById('userfile1').files; 

So now, how can I assign the second image selected to the second input file

userfile2

Because I want to resume the upload as before? It is not working with me and I read that there is security concerns to update the input file, but I need to assign what the user selected, not a path.

I don't want to use the FromData with AJAX as that will lead to change all my code and also it is not compatible with all browsers like my code.

Thanks a lot for your help!

回答1:

It is not possible to assign a File object to an input type="file" element using javascript . File object should be selected by user. It is possible to select a single or mutiple File objects from a FileList returned from multiple File selection and send that selected file to server as a separate process

document.querySelector("input[name=files]")
  .addEventListener("change", function(event) {
    var files = Array.prototype.slice.call(event.target.files),
      filtered = [];
    for (var i = 0; i < files.length; i++) {
      if (i > 0) filtered.push(files[i])
    };
    if (filtered.length) {
      console.log(files, filtered);
      filtered.forEach(function(file) {
        // do stuff
      })
    }
  })
<input name="files" type="file" accept="image/*" multiple="true" />


The problem now, when I select multiple images to upload (let's say two images together using Ctrl), using the first input file, I get them in this array

Note, the FileList object returned by multiple files being selected is not an Array .

See also input file to array javascript/jquery , Trigger click on input=file on asynchronous ajax done() , Simulate drop file event