每天记录一个小知识5-----vue解决后端返回blob文件下载问题

1.首先需要在下载的接口地方加上  responseType: 'blob',

export function download(data) {
  return request({
    url: '',
    method: '',
	data,
	responseType: "blob",
  })
}

responseType的几种类型:

responseType值xhr.response 数据类型说明
" "String字符串默认值(在不设置responseType时)
textString字符串
documentDocument对象希望返回 XML 格式数据时使用
jsonjavascript对象存在兼容性问题,IE10/IE11不支持
blobBlob对象
arrayBufferArrayBuffer对象

2.写一个下载方法:

download(res, Name) {
			  if (!res.data) {
			    return
			  }
			  const blob = new Blob([res.data], {
			    type: "application/vnd.ms-excel"
			  })
			  const fileName = Name ? Name : ''
			  if ('download' in document.createElement('a')) { // 非IE下载
			    const e= document.createElement('a')
			    e.download = fileName + '.xlsx'
			    e.style.display = 'none'
			    e.href = URL.createObjectURL(blob)
			    document.body.appendChild(e)
			    e.click()
			    URL.revokeObjectURL(e.href) // 释放URL 对象
			    document.body.removeChild(e)
			  } else { // IE10+下载
			    navigator.msSaveBlob(blob, fileName)
			  }
			},

不同格式的文件对应的type :

文件类型type
.docapplication/msword
.docxapplication/vnd.openxmlformats-officedocument.wordprocessingml.document
.xlsxapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xlsapplication/vnd.ms-excel
.txt

text/plain

.pptapplication/vnd.ms-powerpoint
.pptxapplication/vnd.openxmlformats-officedocument.presentationml.presentation

3.调用接口

downloadList(){
    download(data).then(res=>{
		this.download(res,'例如');//后端数据及文件名称
	});
}

学习记录   如有侵权请联系删除

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值