Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 891
Drag0 Avatar asked Apr 06 '16 14:04

Drag0


People also ask

How do I get my fetch progress?

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.

How fetch data from API and display in JavaScript?

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.


1 Answers

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))
like image 162
Zamboney Avatar answered Oct 09 '22 16:10

Zamboney