I'm new to Javascript and jQuery. While uploading N number of files in the form, only the last file is uploaded N times,
I'm want to upload each file one at a time (Asynchronously) through AJAX request.
Below is my implementation:
$("#file-input").on("input", function() { var formdata = new FormData(document.getElementById("file-catcher")); $.each($("#file-input")[0].files, function (key, file){ formdata.append(key, file); // This is to Inspecting each file for(var pair of formdata.entries()) { console.log(pair[0]+ ': '+ pair[1]); } // Sending AJAX $.ajax({ type: "POST", data: formdata, url: "/url/to/upload", datatype: 'JSON', contentType: false, cache: false, processData: false, success:function(data){ console.log(data); // Inspecting Response }, error: function (error) { console.log(error); // Inspecting Error if occured } }); }); });
<form method="POST" id="file-catcher" action="/url/to/upload" enctype="multipart/form-data"> <input type="text" name="fileCode" value="10"> <input type="file" id="file-input" name="file-input" multiple> </form>
I would like to give credit to Chris G for guiding me to iterate through each file to create a queue and send files in the sequence.
const inputFile = document.getElementById('file-input');
// Iterating through each file and sending AJAX request
for (const file of inputFile.files){
var formdata = new FormData(document.getElementById("file-catcher"));
formdata.append("file-input", file);
$.ajax({
type: "POST",
data: formdata,
url: "/url/to/upload",
datatype: 'JSON',
contentType: false,
cache: false,
processData: false,
success:function(data){
console.log(data);
},
error: function (error) {
console.log(error);
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.