如何使用fetch()和WhatWG流获得文件上传进度 [英] How to get File upload progress with fetch() and WhatWG streams

查看:456
本文介绍了如何使用fetch()和WhatWG流获得文件上传进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我没有寻找任何替代方法.我知道可以使用XMLHttpRequest完成.我也不在乎浏览器的支持.我只想了解新标准/即将推出的标准.

我有一个文件对象,我可以上传它像这样使用PUT使用PUT:

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?

据我了解,获取选项的body可以是 ReadableStream .那么也许有一种方法可以将File对象包装到ReadableStream并从中获取进度状态?

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?

例如.像这样的东西

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

谢谢.

推荐答案

正如Kyle所说,尚不支持ReadableStream上传. https://github.com/whatwg/fetch/issues/95

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

即使有可能,我也不会尝试通过流监视上传进度(即,如果 FetchObserver 变成一个东西)现在没有人在处理它.但是Mozilla提出了一个看起来像这样的提议.

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)
  }
)

我记得很久以前我使用一些实验性标志对其进行了测试,但由于找不到演示,所以他们将其从MDN中删除了,因为它是自己的实现/建议.

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.

这篇关于如何使用fetch()和WhatWG流获得文件上传进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆