Reputation: 31
If you have an HTML form with an element like this:
<input type="file" name="file" multiple="multiple">
Then normally it would allow the user to select multiple files to upload, and they all get sent to the server with the same form field name "file".
I understand that due to security reasons, browsers won't let JavaScript just set any value for the selected files, and that's a good thing.
I just wonder though, once the user has selected the files, I would like to have multiple forms perform the uploads individually. Is there a way to either:
Upvotes: 3
Views: 973
Reputation: 1074138
If you clone an input[type=file]
element, the clone's value is blank. You also cannot copy the value from one file input to another.
I've never tried to move a file input from one document to another after the file is selected. I'd like to think the browser would clear the selection when you did that, too, but it may not. (Update: Of three browsers tested, all of them retained the value, to my surprise. See below.)
Fundamentally, if you want to use separate forms to upload the files individually, you'll want the inputs in separate forms to begin with, before the user makes their selections. But apparently you may be able to move them, which would let you do what you want to do. I'd still probably start out with separate forms, to avoid having to move them.
Interestingly, Chrome, Firefox, and IE10 at least seem perfectly happy to move a file element with its selection intact, even to a different document: Live Example | Source
HTML:
<input id="theFile" type="file">
<br>Choose a file above, then either:
<br><input type="button" id="btnClone" value="Clone">
<input type="button" id="btnMove" value="Move to iframe">
<br>
<iframe id="theFrame" style="width: 99%"></iframe>
JavaScript:
(function() {
gid("btnClone").onclick = function() {
display("Here's the clone:");
document.body.appendChild(gid("theFile").cloneNode(true));
};
gid("btnMove").onclick = function() {
gid("theFrame").contentDocument.body.appendChild(gid("theFile"));
display("File input moved to the iframe");
};
function gid(id) {
return document.getElementById(id);
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
With the above, if I select something and click the Move to iframe button, the input is moved, apparently intact. (Cloning clears the value, as expected.)
Upvotes: 2