【问题标题】:jquery then and fetch src - upload images to serverjquery 然后获取 src - 将图像上传到服务器
【发布时间】:2018-01-07 19:57:01
【问题描述】:

我想一次将图像文件列表传递给服务器。

这是我的代码,其中函数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 }); })
    );
}

在这种情况下如何使用formData

【问题讨论】:

  • 您是否从您的开发者工具中检查了 http 请求?图片文件是否包含在您的请求中?
  • 预期结果是什么?
  • @Jesse 我从表行的列中得到“src”(绑定到表之前:var src = URL.createObjectURL(file);)

标签: javascript jquery arrays promise


【解决方案1】:

srcToFile返回的所有promise放入一个数组,然后使用$.when()等待所有的promise。

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(...)

【讨论】:

  • 谢谢@Barmar!我试过了,它显示长度 = 0。我可能错了吗?我调试并看到 formData.append 在警报之后运行。
猜你喜欢
  • 1970-01-01
  • 2017-04-28
  • 2022-09-26
  • 2013-02-01
  • 1970-01-01
  • 2017-06-22
  • 2013-12-17
  • 2014-03-21
  • 2017-05-31
相关资源
最近更新 更多