[英]jquery then and fetch src - upload images to server
I want to pass a list of image files to the server at once. 我想一次将图像文件列表传递到服务器。
This is my code, where the function srcToFile
is for creating a new file as image. 这是我的代码,其中srcToFile
函数用于将新文件创建为图像。
var formData = new FormData();
// Iterate all td's in second column
$("#table-image tbody tr:not(:first-child)").each(function (index, value) {
var blob = value.cells[4].innerText;
var fileName = (index + 1) + ".jpg";
srcToFile(blob, fileName, "image/jpeg")
.then(function (file) {
formData.append("file", file);
alert(formData.getAll("file").length); ** // I know that I can use aJax jquery to pass one by one at here**
}, function (error) {
//
});
});
function srcToFile(src, fileName, mimeType) {
return (fetch(src)
.then(function (res) { return res.arrayBuffer(); })
.then(function (buf) { return new File([buf], fileName, { type: mimeType }); })
);
}
How can I use formData
in this case? 在这种情况下如何使用formData
?
Put all the promises returned by srcToFile
into an array, then use $.when()
to wait for all of them. 将srcToFile
返回的所有srcToFile
放入数组中,然后使用$.when()
等待所有这些srcToFile
。
var promises = $("#table-image tbody tr:not(:first-child)").map(function (index, value) {
var blob = value.cells[4].innerText;
var fileName = (index + 1) + ".jpg";
return srcToFile(blob, fileName, "image/jpeg")
.then(function (file) {
formData.append("file[]", file);
}, function (error) {
//
});
}).get();
$.when(promises).then(function() {
alert(formData.getAll("file[]").length);
return $.ajax({
url: "yourURL",
type: "post",
processData: false,
data: formData
});
}).then(...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.