How to get File upload progress with fetch() and WhatWG streams

好久不见. 提交于 2019-12-21 07:35:16

问题


Note: I'm not looking for any alternatives. I know this can be done with XMLHttpRequest. I also don't care about browser support. I just want learn about the new/upcoming standards.

I have a File object and I can upload it with PUT using fetch like this:

fetch(url, {
    method: "PUT",
    body: fileObject,
});

How can I get upload progress from this?

From what I understand the body of the fetch options can be a ReadableStream. So maybe there is a way to wrap the File object to a ReadableStream and get progress status from that?

Eg. something like this

fetch(url, {
    method: "PUT",
    body: asReadableStream(fileObject, onProgress),
});

Thanks.


回答1:


As Kyle said, ReadableStream uploading is not supported yet. https://github.com/whatwg/fetch/issues/95

Even if it where possible I would not try to monitor the upload progress throught streams, (that is if FetchObserver becomes a thing) Nobody is working on it right now. But Mozilla made a proposal that looks something like this.

/*
enum FetchState {
  // Pending states
  "requesting", "responding",

  // Final states
  "aborted", "errored", "complete"
};
*/

fetch(url, {
  observe(observer) { 
    observer.onresponseprogress = e => console.log(e);
    observer.onrequestprogress = e => console.log(e);
    observer.onstatechange = n => console.log(observer.state)
  }
)

I remember that i tested it using some experimental flags a long time ago but can't find the demo anymore, guess they removed it from MDN since it was there own implementation/suggestion.




回答2:


Short answer: cannot be done right now.

Checkout the spec here: https://fetch.spec.whatwg.org/#fetch-api

Second sentence indicates that there isn't a way to track request progression when using fetch.

The fetch() method is relatively low-level API for fetching resources. It covers slightly more ground than XMLHttpRequest, although it is currently lacking when it comes to request progression (not response progression).



来源:https://stackoverflow.com/questions/52422662/how-to-get-file-upload-progress-with-fetch-and-whatwg-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!