您需要从数据创建一个 urlBlob https://developer.mozilla.org/en/docs/Web/API/Blob,并将其添加到 href 并触发点击。
let url;
const saveData = (() => {
const a = document.createElement('a');
a.style = 'display: none';
document.body.appendChild(a);
return (data, fileName, type = 'octet/stream') => {
const blob = new Blob([data], { type });
if (navigator.msSaveBlob) {
return navigator.msSaveBlob(blob, fileName);
}
if (url) {
// Keep at most 1 blob around by removing the last used one.
URL.revokeObjectURL(url);
}
url = URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
return true;
};
})();
因此,这个函数将获取您的数据并执行这两个步骤,您可以像这样使用它:
$.ajax({
method: "POST",
contentType: "application/x-www-form-urlencoded",
url: "<endpoint here>",
data: {
"tokenId": token,
"downloadId": "cz98567354",
"saveAs": "AllContents"
}
})
.done((data) => saveData(data, 'myDownload.zip'));
请注意,对于不支持 Blob 的过时浏览器,还有另一种方法可以使用window.open
使用 Base64 编码的数据字符串。另请注意,我提供的函数使用箭头函数和默认参数,但如果您愿意,可以很容易地对其进行 ES5 化。