Upload file with Fetch API in Javascript and show progress [duplicate]

雨燕双飞 提交于 2019-11-29 02:56:33

问题


This question already has an answer here:

  • Upload progress indicators for fetch? 8 answers

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?


回答1:


This is NOT possible. The reason is the way the Fetch API works.

The fetch method returns a Promise; the Promise API uses a then method to which you can attach “success” and “failure” callbacks. Therefore, you can gain access to progress.

Still, don't lose hope! There is a workaround that can do the trick (I found it on github repository of the Fetch API):

you can convert the request to a stream request and then when a response return is just a bitarray of the file content. then you need to collect all of the data and when its end decode it to the file you want

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


来源:https://stackoverflow.com/questions/36453950/upload-file-with-fetch-api-in-javascript-and-show-progress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!