Download multiple HTML5 AJAX files

I came across this simple js ajax download code (it seems that jquery $.post doesn't 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 questions,

  • What does this line mean after the FormData object?

fd.append("file", document.getElementById('file').files[0]);

Why do I need an identifier? Is it possible to use jquery append() something with $('input[type=file]') ?

  • This ajax is only for uploading a single file, how can I change it to upload multiple files?
+4
source share
1 answer

What does this line mean after the FormData object?

 fd.append("file", document.getElementById('file').files[0]); 

document.getElementById('file') gets the <input type="file" id="file"> element by its identifier. element.files[0] captures the first selected file from the element. fd.append("file", file) attaches it to the FormData instance with the field name file . fd later sent as the body of the multipart/form-data XHR request.


Why do I need an identifier? Is it possible to use jquery append() with $('input[type=file]') something?

No identifier required. After all, this is just an example to get <input type="file"> from a document by its identifier. Note that the append() function in this example is part of the FormData API and should not be confused with the jQuery append() function. Also note that the first argument to append() represents the name of the field, not the identifier. The fact that they are the same is just a coincidence.


This ajax is only for uploading a single file, how can I change it to upload multiple files?

Just add a few fields to FormData . Assuming you have File[] , here is an example:

 for (var i = 0; i < files.length; i++) { fd.append("file" + i, files[i]); } 

It will be available on the server with the field names file0 , file1 , etc.

+9
source

All Articles