【发布时间】:2019-03-03 11:41:33
【问题描述】:
所以我正在尝试下载一个对我的 api 进行 ajax 调用的 zip 文件。该 api 以一个 base 64 编码的字节数组响应。现在对于大多数下载来说,这工作得很好,但是当 zip 文件变得太大时,它开始在 Chrome 中失败。在所有其他浏览器中都能正常工作。从我在堆栈溢出中发现的内容来看,这是 chrome 中的一个已知问题,人们建议使用 blob。事情是我正在使用 blob 并且仍然有问题。这是我处理下载的代码。我通过为 contentType 传递不同的值来使用它来下载 pdf 和 zip 文件。有没有人遇到过这个问题?是否有任何解决方法或脚本可以添加到页面来解决这个问题?
// data is base 64 encoded byte array
function download(data, filename, contentType) {
var byteCharacters = atob(data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], { type: contentType });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
// IE / edge workaround
window.navigator.msSaveOrOpenBlob(blob, filename);
} else if (navigator.userAgent.indexOf("Firefox") > 0) {
var a = window.document.createElement('a');
a.download = filename;
a.style.cssText = "display: none";
a.target = "_blank";
// Append anchor to body.
document.body.appendChild(a);
a.href = "data:" + contentType + ";base64," + data;
a.click();
// Remove anchor from body
document.body.removeChild(a);
} else //Chrome, safari, etc
{
var a = document.createElement("a");
a.style = "display: none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}
}
【问题讨论】:
-
即使您克服了所有问题,谷歌浏览器也有自己的网络超时,很遗憾您无法更改它。检查这个superuser.com/questions/633648/…
-
它实际上不是超时错误,chromes 错误消息只是让它看起来那样。 Api 的响应速度足够快,它只是特定于 chrome 如何以这种方式处理下载
-
@victor 你能看看我下面的答案,让我知道它是否有效吗?在此先感谢...
-
@victor 面临完全相同的问题,有没有适合您的解决方案?
标签: javascript ajax google-chrome