I came across this plain js ajax upload code (it seems that jquery $.post does not work with HTML5 for some reason),
/* If you want to upload only a file along with arbitary data that
is not in the form, use this */
var fd = new FormData();
fd.append("file", document.getElementById('file').files[0]);
/* If you want to simply post the entire form, use this */
//var fd = document.getElementById('form1').getFormData();
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "Upload.php");
xhr.send(fd);
But I have two issues here,
- what does this line mean after the object
FormData?
fd.append("file", document.getElementById('file').files[0]);
Why do I need an ID there? Can I do something use jquery append() with $('input[type=file]')?
- This ajax is only for single file upload, how can I change it for multiple files upload?
The
document.getElementById('file')gets the<input type="file" id="file">element by its ID. Theelement.files[0]grabs the first selected file from the element. Thefd.append("file", file)appends it to anFormDatainstance with the field name offile. Thefdis later to be sent asmultipart/form-dataXHR request body.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 theappend()function in this example is part of theFormDataAPI and is not to be confused with jQuery’sappend()function. Also note that the 1st argument ofappend()represents the field name, not the ID. That they are the same is just a coincidence.Just append multiple fields to
FormData. Assuming that you have aFile[], here’s an example:It’ll be available in the server end by the field names
file0,file1, etc.