[英]Multiple File Upload using AJAX in sequence/queue
I'm new to Javascript and jQuery.我是 Javascript 和 jQuery 的新手。 While uploading N number of files in the form, only the last file is uploaded N times,在表单中上传N个文件时,只上传最后一个文件N次,
I'm want to upload each file one at a time (Asynchronously) through AJAX request.我想通过 AJAX 请求一次(异步)上传每个文件。
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.我要感谢Chris G指导我遍历每个文件以创建队列并按顺序发送文件。
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);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.