Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  122] [ 4]  / answers: 1 / hits: 21811  / 8 Years ago, wed, april 6, 2016, 12:00:00

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?


More From » upload

 Answers
35

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

[#62670] Monday, April 4, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josefn

Total Points: 251
Total Questions: 93
Total Answers: 84

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;