【前端二进制流文件下载】

前端接口调用

this.axios.post("/api/doorStatistics/exportEarlyWarningData", params,{
		timeout: 0,
		responseType: "blob",
		headers: {
			"Content-Type": "application/json;application/octet-stream"
		}
	}).then(res => {
       console.log(res);
       let fileName = item.title+item.version;
		this.$utils.binaryDownload(res,fileName);//具体下载方法在下方
})

后端返回数据

显示

显示乱码

打印res

打印显示数据信息]

二进制流下载方法

binaryDownload(res,cfileName) {
	if (!res.data) {
		this.$message.error("文件下载失败!");
		return false;
	}

	// 这里res.data是返回的是二进制文件流
	const blob = new Blob([res.data], { type: 'application/octet-stream;charset=utf-8', endings: 'transparent' }); // 将二进制文件流转为blob

	let contentDisposition = res.headers['content-disposition']; // 从Response Headers中获取content-disposition的值, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
	let patt = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; // 设置正则表达式匹配格式
    let result = patt.exec(contentDisposition); // 通过正则表达式提取“filename=” 后的值
    let filename = result[1]; // 提取文件名
    let list = filename.split('.');
    let suffix = list[list.length-1];
	// 兼容IE,window.navigator.msSaveBlob:以本地方式保存文件
	if (typeof window.navigator.msSaveBlob !== 'undefined') {
		window.navigator.msSaveBlob(blob, decodeURI(filename));
	} else {
		const blobURL = window.URL.createObjectURL(blob); // 把blob转化为一个Blob URL

		const aLink = document.createElement('a'); // 创建a标签,用于跳转至下载链接
		aLink.href = blobURL; // 设置a标签href值
      if(cfileName){
        aLink.setAttribute('download', decodeURI(cfileName +'.'+ suffix)); // 设置下载文件名称
      }else{
        if (res.config.params.fileType == undefined || res.config.params.fileType == '' || res.config.params.fileType == null) {
          aLink.setAttribute('download', res.config.params.fileName); // 设置下载文件名称
        } else {
          aLink.setAttribute('download', res.config.params.fileName + '.' + res.config.params.fileType); // 设置下载文件名称
        }
      }
			
		// 兼容:某些浏览器不支持HTML5的download属性
		if (typeof aLink.download === 'undefined') {
			aLink.setAttribute('target', '_blank');
		}
		aLink.style.display = 'none'; // 隐藏a标签
		document.body.appendChild(aLink); // a标签插入到body中
		aLink.click(); // 模拟a标签点击事件 使其下载
		document.body.removeChild(aLink); // 移除a标签
		window.URL.revokeObjectURL(blob); //释放掉blob对象
	}
},
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值