通过jQuery下载八位字节流
我已经实现了以下代码:
我有一个像这样的html按钮:
HTML
在downCont()
调用的downCont()
函数是一个像这样的ajax POST
:
JQuery的
var downCont = function() { $.ajax({ method: "POST", contentType: "application/x-www-form-urlencoded", url: "", data: { "tokenId": token, "downloadId": "cz98567354", "saveAs": "AllContents" } }) .done(function() { alert("I have downloaded all contents!"); }); });
现在,此POST
请求的响应用于下载直接流式传输给用户的图像存档(content-type: application/octet-stream)
。 如何使用jQuery
触发浏览器本身的归档下载?
您需要从数据Blob创建一个URL,并将其添加到href并触发单击。
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); } const url = URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); URL.revokeObjectURL(url); return true; }; })();
因此,此函数将获取您的数据并执行这两个步骤,您可以使用以下内容:
$.ajax({ method: "POST", contentType: "application/x-www-form-urlencoded", url: "", data: { "tokenId": token, "downloadId": "cz98567354", "saveAs": "AllContents" } }) .done((data) => saveData(data, 'myDownload.zip'));
请注意,对于不支持Blob的过时浏览器,还有一种使用base64编码数据字符串的window.open
的替代方法。 另外请注意我提供的function使用箭头function和默认args,但如果你愿意,可以很容易地ES5’。