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?
Asked
Active
Viewed 2.2k times
1 Answers
11
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))

sideshowbarker
- 81,827
- 26
- 193
- 197

Zamboney
- 2,002
- 12
- 22
-
1You forget to mention that the response should be stream otherwise it won't work: From the git comment: `...and you'll also be able to provide a readable stream when creating responses too. Streams everywhere` – Sadok Mtir Feb 27 '18 at 10:24
-
61Can someone clarify? This answer seems to track progress of a download, not an upload. – goldins Mar 01 '18 at 02:03
-
Yes, doesn't this track download instead of upload? Or is it like a ping pong of chunks of bytes between the server and the client where the server (as soon as it receives a new chunk of bytes) sends the received chunk back to the client so that the client knows that the server has received the chunk it previously sent? – tonix Jul 23 '19 at 19:57