javascript 如何使用fetch()和WhatWG流获取文件上传进度

rxztt3cl  于 2022-12-02  发布在  Java
关注(0)|答案(2)|浏览(196)
  • 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.

ca1c2owp

ca1c2owp1#

更新

Chrome开始支持流媒体上传https://chromestatus.com/features/5274139738767360
下面是一个使用拉流的演示,当请求准备好接受更多数据进行上传时,请求会调用该拉流

let uploaded = 0
let buf = new Uint8Array(1024 * 50)
let start = Date.now()

var rs = new ReadableStream({
  pull(ctrl) {
    uploaded += buf.byteLength
    console.log('uploaded', uploaded)
    crypto.getRandomValues(buf)
    ctrl.enqueue(buf)
    if ((start + 1000) < Date.now()) ctrl.close()
  }
})

fetch('https://httpbin.org/post', {
  method: 'POST',
  body: rs,
  duplex: 'half'
}).then(r => r.json()).then(console.log)

正如凯尔所说,目前还不支持ReadableStream上传。https://github.com/whatwg/fetch/issues/95
即使有可能,我也不会尝试通过流来监控上传进度,(如果FetchObserver成为一个东西的话)现在还没有人在做这件事。但是Mozilla提出了一个类似这样的建议。

/*
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中删除了它,因为它是自己的实现/建议。
将字节入队到可读流或标识流并不意味着您已经将数据上载到服务器,它只是表明请求更多数据的请求可能会填满一个桶

eimct9ow

eimct9ow2#

简短回答:现在还做不到。
请在此处查看规格:https://fetch.spec.whatwg.org/#fetch-api
第二句话指出,在使用fetch时,没有跟踪 request 进程的方法。
fetch()方法是用于获取资源的相对低级的API,它比XMLHttpRequest覆盖的范围稍大,尽管它目前在请求进程(而不是响应进程)方面有所欠缺。

相关问题