【js】web前端:文件下载

在这里插入图片描述

// 返回二进制
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下
使用相对路径

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值