Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get progress from Fetch API? [duplicate]

I'm using $.ajax,i can do that:

var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
  if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
    //Do something with upload progress
    console.log(percentComplete);
  }
}, false);

But,when i use fetch api,what should i do?

var fData = new FormData();
fData.append("userfile",document.getElementById("file").files[0]);
fetch("/", {method:"POST",body:fData}).then(function(res){});
like image 486
huiting Chen Avatar asked Jun 14 '16 08:06

huiting Chen


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 do I retrieve data from a fetch request?

How do I return a response on Fetch? Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

How do I display fetch data from API?

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

As of right now, you can't. It's not part of the spec yet. There was an issue for it on the spec's repo but it's closed. There's also some discussion on this issue about it.

Long story short, you are probably better off just sticking with xhr for now unless you want to try some of the polyfills/workarounds in the second issue Iinked.

It's just not supported, and that is also the reason fetch requests don't show up in the network tab in the devtools untill they've completed.

like image 130
ivarni Avatar answered Oct 01 '22 02:10

ivarni