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?
To track download progress, we can use response. body property. It's a ReadableStream – a special object that provides body chunk-by-chunk, as it comes. Readable streams are described in the Streams API specification.
Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With