// 返回二进制
var xhr = new XMLHttpRequest();
xhr.open(
"GET",
`${url}/web/showWordDownload?companyId=${that.companyId}`,
true
);
xhr.responseType = "blob";
xhr.onload = function(e) {
let content = xhr.response;
let blob = new Blob([content], { type: "application/pdf" });
let explorer = window.navigator.userAgent;
if (explorer.indexOf("Trident") < 0) {
let a = document.createElement("a");
a.download = "工控系统安全加固建议报告.docx";
a.style.display = "none";
a.href = URL.createObjectURL(blob);
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
} else {
var blobObject = new Blob([content],
{type: "application/pdf" });
navigator.msSaveBlob(
blobObject,
"工控系统安全加固建议报告.docx"
);
}
};
xhr.send();
Blob对象:
存放二进制数据的容器。处理二进制数据。
创建:
var blob = new Blob(dataArray, opt: { type: string});
// dataArray:数组,数据可以是任意多个ArrayBuffer,
//ArrayBufferView, Blob,或者 DOMString对象。
应用场景:
1、通过URL链接下载文件。demo如下:
function downFile () {
let content = 'test test, 测试2019-11-11!!!';
let blob = new Blob([content]);
let url = URL.createObjectURL(blob);// 下载链接
let a = document.createElement('a');
document.body.appendChild(a)
a.innerHTML = '点击下载';
a.download = 'test.docx';
a.href = url;
}
downFile();
下载base64的图片
后台返回base64的图片, 前端进行下载。
downLoad(base64) {
const imgUrl = 'data:image/png;base64,' + base64;
const fileName = `${this.currentRow.sellerName}_${this.currentRow.operator}`;
// ie
if (window.navigator.msSaveOrOpenBlob) {
let bstr = atob(imgUrl.split(",")[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
let blob = new Blob([u8arr]);
window.navigator.msSaveOrOpenBlob(blob, fileName + "." + "png");
} else {
// chrome等新版浏览器
let a = document.createElement("a");
a.href = imgUrl;
a.setAttribute("download", fileName);
a.click();
}
3、下载静态文件(static)
<a href="../../../static/wen.exe" download="某文件.exe">下载客户端软件</a>
注意:
资源放在static下
使用相对路径