我正在使用此代码从我的网络 API 下载文件:
function download(name){
axios.get(api + "?filename="+name, { responseType: 'blob' })
.then(res => {
let blob = new Blob([res.data]);
let a = document.createElement("a");
document.body.appendChild(a);
a.href = window.URL.createObjectUrl(blob);
a.download = name;
a.click();
window.URL.revokeObjectUrl(url);
a.remove();
}
);
}
当下载小文件时这段代码很棒,但当下载大文件时(例如 400mb) 代码等待 blob 读取全部内容,然后才在 chrome 下载管理器中“开始下载”,这对客户端来说非常不直观。
有没有办法将 blob“流”到文件系统?而不是必须等待文件完全到达我客户端的 RAM,然后才在下载管理器中显示下载?
已解决
我没有通过 axios 库下载文件,而是将浏览器指向下载链接,因为它只是一个 GET 请求。
function download(name){
let a = document.createElement("a");
document.body.appendChild(a);
a.href = api + "?filename="+name;
a.click();
a.remove();
}
只需要将服务器端的 ContentDisposition header 设置为附件,并指定一个文件名,因为下载属性在某种程度上不适用于此方法。
同时指定 ContentLength 将允许浏览器估计下载时间
最佳答案
如果您需要下载 POST
请求的响应或者您的请求需要某种高级身份验证,而不是使用 axios
库,您可以尝试使用 native fetch
方法。
fetch(options)
.then(res => res.blob())
.then(blob => {
// use blob
});
您可以查看完整的response
API here .
关于javascript - 快速 blob 下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53913512/