我已经实现了以下代码:
我有一个这样的 html 按钮:
HTML
<button style="background-color: #f39900;" onclick="downCont()">
Download all content
</button>
Run Code Online (Sandbox Code Playgroud)
downCont()单击时调用的函数是ajax POST这样的:
查询
var downCont = function() {
$.ajax({
method: "POST",
contentType: "application/x-www-form-urlencoded",
url: "<endpoint here>",
data: {
"tokenId": token,
"downloadId": "cz98567354",
"saveAs": "AllContents"
}
})
.done(function() {
alert("I have downloaded all contents!");
});
});
Run Code Online (Sandbox Code Playgroud)
现在,此POST请求的响应用于下载直接流式传输给用户的图像存档(content-type: application/octet-stream)。如何通过浏览器本身使用 触发下载档案jQuery?
您需要从数据Blob创建一个 url ,并将其添加到一个 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;
};
})();
Run Code Online (Sandbox Code Playgroud)
所以这个函数将获取你的数据并执行这两个步骤,你可以像这样使用它:
$.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'));
Run Code Online (Sandbox Code Playgroud)
请注意,对于不支持 Blob 的过时浏览器,还有一种window.open使用 base64 编码数据字符串的替代方法。另请注意,我提供的函数使用箭头函数和默认参数,但如果您愿意,可以轻松地将其进行 ES5 化。