一种可能的解决方法是利用
new Request()
构造函数,然后检查
Request.bodyUsed
Boolean
属性。
bodyUsed
属性的getter如果disturbed
则返回true,否则返回false。
通过判断流是否distributed
来确定是否使用.then()
链接到递归.read()
调用的ReadableStream
中的fetch()
Promise
。
实现Body
mixin的对象如果body
非空且其stream
被disturbed
,则称为disturbed
。
请注意,该方法不会读取Request.body
的字节,因为字节会被流式传输到终点。此外,在完全返回响应之前,上传可能已经完成。
const [input, progress, label] = [
document.querySelector("input")
, document.querySelector("progress")
, document.querySelector("label")
];
const url = "/path/to/server/";
input.onmousedown = () => {
label.innerHTML = "";
progress.value = "0"
};
input.onchange = (event) => {
const file = event.target.files[0];
const filename = file.name;
progress.max = file.size;
const request = new Request(url, {
method: "POST",
body: file,
cache: "no-store"
});
const upload = settings => fetch(settings);
const uploadProgress = new ReadableStream({
start(controller) {
console.log("starting upload, request.bodyUsed:", request.bodyUsed);
controller.enqueue(request.bodyUsed);
},
pull(controller) {
if (request.bodyUsed) {
controller.close();
}
controller.enqueue(request.bodyUsed);
console.log("pull, request.bodyUsed:", request.bodyUsed);
},
cancel(reason) {
console.log(reason);
}
});
const [fileUpload, reader] = [
upload(request)
.catch(e => {
reader.cancel();
throw e
})
, uploadProgress.getReader()
];
const processUploadRequest = ({value, done}) => {
if (value || done) {
console.log("upload complete, request.bodyUsed:", request.bodyUsed);
return reader.closed.then(() => fileUpload);
}
console.log("upload progress:", value);
progress.value = +progress.value + 1;
return reader.read().then(result => processUploadRequest(result));
};
reader.read().then(({value, done}) => processUploadRequest({value,done}))
.then(response => response.text())
.then(text => {
console.log("response:", text);
progress.value = progress.max;
input.value = "";
})
.catch(err => console.log("upload error:", err));
}
fetch
API的解决方案:https://fetch.spec.whatwg.org/#fetch-api。就请求进度而言,它目前还存在缺陷(不是响应进度)。 - fguillen