16

I'm using Fetch API in Javascript to upload big file to server. Is there any event in Fetch API that I could use to track progress of upload?

4

1 回答 1

11

这是不可能的。原因是 Fetch API 的工作方式。

fetch方法返回一个 Promise;Promise API 使用一种then方法,您可以将“成功”和“失败”回调附加到该方法。因此,您可以获得进度。

不过,不要失去希望!有一种解决方法可以解决问题(我在 Fetch API 的github存储库中找到了它):

您可以将请求转换为流请求,然后当响应返回只是文件内容的位数组时。那么您需要收集所有数据,并在其结束时将其解码为您想要的文件

function consume(stream, total = 0) {
  while (stream.state === "readable") {
    var data = stream.read()
    total += data.byteLength;
    console.log("received " + data.byteLength + " bytes (" + total + " bytes in total).")
  }
  if (stream.state === "waiting") {
    stream.ready.then(() => consume(stream, total))
  }
  return stream.closed
}
fetch("/music/pk/altes-kamuffel.flac")
  .then(res => consume(res.body))
  .then(() => console.log("consumed the entire body without keeping the whole thing in memory!"))
  .catch((e) => console.error("something went wrong", e))
于 2016-04-06T14:50:23.097 回答