【发布时间】:2018-04-06 12:44:54
【问题描述】:
我需要使用 XMLHttpRequest 或 fetch 使用 JavaScript 下载一个大文件,而无需先将文件保存在 RAM 内存中。
普通链接下载对我不起作用,因为我需要在请求的标头中发送承载令牌。
我可以设法下载一个文件,但是这个“解决方案”,它首先将文件保存在 RAM 内存中,然后我得到一个保存对话框,这样如果文件大于可用 RAM,浏览器就会停止-内存。
这是我使用 fetch 的“解决方案”:
var myHeaders = new Headers();
myHeaders.append('Authorization', `Bearer ${token}`);
var myInit = { method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default' };
var a = document.createElement('a');
fetch(url,myInit)
.then((response)=> {
return response.blob();
})
.then((myBlob)=> {
a.href = window.URL.createObjectURL(myBlob);
var attr = document.createAttribute("download");
a.setAttributeNode(attr);
a.style.display = 'none';
document.body.appendChild(a);
a.click();
a.remove();
});
这是我使用 XMLHttpRequest 的“解决方案”:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = ()=>{
if (xhttp.readyState == 4){
if ((xhttp.status == 200) || (xhttp.status == 0)){
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhttp.response); // xhr.response is a blob
var attr = document.createAttribute("download");
a.setAttributeNode(attr);
a.style.display = 'none';
document.body.appendChild(a);
a.click();
a.remove();
}
}
};
xhttp.open("GET", url);
xhttp.responseType = "blob";
xhttp.setRequestHeader('Authorization', `Bearer ${token}`);
xhttp.send();
问题是如何下载大于可用 RAM 内存的文件并同时设置标题?
【问题讨论】:
-
你可以在这里找到答案:stackoverflow.com/questions/4545311/…
-
@juancab jQuery 文件下载接缝不是解决方案,如果我没记错的话,我什至无法发送我的标头(承载令牌)。文件下载接缝只是我已经解决的解决方案,并且正在获得一个保存对话框。我没有测试过,但我认为 jQuery 文件下载会遇到和我一样的问题,那就是下载的文件比 RAM 内存大,如果我错了,请纠正我。
标签: javascript xmlhttprequest fetch-api