Upload file with Fetch API in Javascript and show progress

Drag0 picture Drag0 · Apr 6, 2016 · Viewed 16.6k times · Source

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?

Answer

Zamboney picture Zamboney · Apr 6, 2016

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