how to get multiple file input from a single input

2019-05-10 10:27发布

问题:

Using browser firefox and chrome

I have an input file element.

<input type='file' id='tempFileInput' multiple></input>

Let say I have selected three files for the above file input box ('tempFileInput');

OnChange I want to separate three files into three new file input boxes for each file. i.e

<input type='file' id='inputFile_0'></input> 
<input type='file' id='inputFile_1'></input> 
<input type='file' id='inputFile_2'></input>

I'm struggling to achieve this. Any help?

//I have written a small JavaScript snippet towards what I wana achieve.

var index = 0;
function multipleInputBoxes(tempFileInput){
   var divForm = document.getElementById('divForm');
   var numOfFiles = tempFileInput.files.length;

   for(var i=0; i<numOfFiles; i++){
      var newUploader = document.createElement('input');
      newUploader.type='file';
      newUploader.id = 'inputFile_' + index;

      var file = tempFileInput.files[i];
      ***newUploader.files[0] = file;***
      //above line does not work, as by default due to security reasons input type='file' is read only, and non editable.

      divForm.appendChild(newUploader);
      index++;
   }
}

回答1:

If you are on HTML5, you can select multiple files with one input tag. There no need for additional ones.

Use the HTML5 below:

<input type='file' id='tempFileInput' multiple='multiple'></input>

Update:

There is no way to do what you want. The files attribute is ready only for a reason. It's to prevent uploading files without user's agreement. If it's not read only, then you can script that and upload any files from user's computer, which is a huge security issue.



回答2:

So I was having difficulty accessing file(s) form single fileinput and separately saving them in each form. As I could access each file var file = tempFileInput.files[i], I created a loop and saved each file in a html 'object' tag and saved the file object in object.value. For e.g

var numOfFile = tempFileInput.files.length;
for (var int i=0; i<numOfFile; i++){
    //get file object from the filinput element
    var file = tempFileInput.files[i];

    //create new element
    var newObj = document.createElement('object');
        newObj.id = 'obj_' + i;
        newObj.value = file;

    //append object to new form
    createNewForm(newObj);
}

function createNewForm(newObj){
   ...do something here
   ...
   ...
   newForm.appendChild(newObj);
}