HTML5 AJAX Multiple Files Upload
Solution 1:
what does this line mean after the object FormData?
fd.append("file", document.getElementById('file').files[0]);
The document.getElementById('file')
gets the <input type="file" id="file">
element by its ID. The element.files[0]
grabs the first selected file from the element. The fd.append("file", file)
appends it to an FormData
instance with the field name of file
. The fd
is later to be sent as multipart/form-data
XHR request body.
Why do I need an ID there? Can I do something use jquery
append()
with$('input[type=file]')
?
The ID is not necessary. It's after all just an example in order to be able to get the <input type="file">
from the document by its ID. Note that the append()
function in this example is part of the FormData
API and is not to be confused with jQuery's append()
function. Also note that the 1st argument of append()
represents the field name, not the ID. That they are the same is just a coincidence.
This ajax is only for single file upload, how can I change it for multiple files upload?
Just append multiple fields to FormData
. Assuming that you have a File[]
, here's an example:
for (var i = 0; i < files.length; i++) {
fd.append("file" + i, files[i]);
}
It'll be available in the server end by the field names file0
, file1
, etc.
Post a Comment for "HTML5 AJAX Multiple Files Upload"