Upload progress indicators for fetch?

Asked
Active3 hr before
Viewed126 times

7 Answers

progressupload
90%

Progress events are a high level feature that won't arrive in fetch for now. You can create your own by looking at the Content-Length header and using a pass-through stream to monitor the bytes received.,However, the Streams spec doesn't appear to be quite finished, and I have no idea whether this already works in any fetch implementation.,Connect and share knowledge within a single location that is structured and easy to search.,If you want to receive the body data progressively:

My solution is to use axios, which supports this pretty well:

axios.request({
   method: "post",
   url: "/aaa",
   data: myData,
   onUploadProgress: (p) => {
      console.log(p);
      //this.setState({
      //fileprogress: p.loaded / p.total
      //})
   }
}).then(data => {
   //this.setState({
   //fileprogress: 1.0,
   //})
})
load more v
88%

Currently it is not possible to get file upload progress for fetch() method.,However going by chromeststatus, it is currently in active development. Probably it may be available within a few months.,Till the time upload progress is enabled for fetch(), XMLHttpRequest object can be used to get file uploading progress.,Upload progress in fetch() is going to be possible by using a ReadableStream body.

Till the time upload progress is enabled for fetch(), XMLHttpRequest object can be used to get file uploading progress.

<input type="file" id="file-input" />
load more v
72%

Is there any way I can attach a progress listener to the xhr.upload object used in fetch?,When will it be supported in the fetch?,since I use fetch to upload files, I would find this very useful., The text was updated successfully, but these errors were encountered:

xhr.upload.addEventListener('progress', function() {
   ...
})
load more v
65%

import fetchProgress from 'fetch-progress,Now use fetchProgress method on your fetch calls, try to put this before using response. You can,import fetchProgress method to your project,Progress of response for fetch API. Get progress report of your response called from fetch like percentage, speed, total, transferred, eta and remaining.

Now use fetchProgress method on your fetch calls, try to put this before using response. You can

fetch(this.props.src)
   .then(
      fetchProgress({
         // implement onProgress method
         onProgress(progress) {
            console.log({
               progress
            });
            // A possible progress report you will get
            // {
            //    total: 3333,
            //    transferred: 3333,
            //    speed: 3333,
            //    eta: 33,
            //    percentage: 33
            //    remaining: 3333,
            // }
         },
      })
   )
load more v
75%

The fetch method allows to track download progress.,Please note: there’s currently no way for fetch to track upload progress. For that purpose, please use XMLHttpRequest, we’ll cover it later.,Once again, please note, that’s not for upload progress (no way now with fetch), only for download progress.,To log the progress, we just need for every received fragment value to add its length to the counter.

// instead of response.json() and other methods
const reader = response.body.getReader();

// infinite loop while the body is downloading
while (true) {
   // done is true for the last chunk
   // value is Uint8Array of the chunk bytes
   const {
      done,
      value
   } = await reader.read();

   if (done) {
      break;
   }

   console.log(`Received ${value.length} bytes`)
}
load more v
40%

Next, let's import this function into the main.js file and initialize it: ,This is the UI we will start off with. The progress indicator will visualize the fetch - progress , Add the event listener for fetch-progress , One for whenever a data chunk is read, event fetch-progress.

export default function http(rootUrl) {
   let loading = false;

   let chunks = [];
   let results = null;
   let error = null;

   // let controller = null; // We will get to this variable in a second

   const json = async (path, options, ) => {
      loading = true

      try {
         const response = await fetch(rootUrl + path, {
            ...options
         });

         if (response.status >= 200 && response.status < 300) {
            results = await response.json();
            return results
         } else {
            throw new Error(response.statusText)
         }
      } catch (err) {
         error = err
         results = null
         return error
      } finally {
         loading = false
      }
   }

   return {
      json
   }
}
load more v
22%

Still, all of these years one feature that is available in XMLHttpRequest is the ability to handle file upload progress, missing from the Fetch specification and we are now in the year 2020, almost 2021 and still, there is no across the board way to handle file upload progress. This is the last missing piece before Fetch can truly replace XMLHttpRequest.,The Fetch API might seem new to some, but it’s already five years old with browsers rolling out support in 2015. It was a replacement for the dated XMLHttpRequest which was tedious to work with and a relic of the yesteryear of internet.,You can also reference the w3c-test site to see when Fetch supports ReadableStream objects and the different types of data being passed into them along with the request here.,Understandably, some developers are still learning standards features that were part of ES2015 and subsequent releases, this is another lump of hardwood on the fire (so-to-speak).

fetch(url, {
   method: 'POST',
   body: stream,
   allowHTTP1ForStreamingUpload: true
});

Other "progress-upload" queries related to "Upload progress indicators for fetch?"