需求:通过Blob下载excel文件,并修改文件名
后端返回的文件流
Blob
Blob
对象表示一个不可变、原始数据的类文件对象。它的数据可以按文本或二进制的格式进行读取,也可以转换成 ReadableStream 来用于数据操作。Blob 表示的不一定是JavaScript原生格式的数据。File 接口基于
Blob
,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。详细了解请移步:Blob - Web API 接口参考 | MDN
贴代码
1、基于vue,以post请求方式导出excel文件
2、responseType设为blob,返回的文件流将会被转成blob对象
3、首先检测当前浏览器是否支持download属性:'download' in document.createElement('a')
注:download该属性是HTML5新增的属性,该属性是让浏览器下载URL而不是跳转到URL所指向的地方
download () {
let filename = '重命名文件名'
this.$http({
url: url,
method: 'post',
responseType: 'blob',
params: {}
}).then(res => {
if ('download' in document.createElement('a')) {
let url = window.URL.createObjectURL(res.data)
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', filename + '.xlsx')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} else {
navigator.msSaveBlob(res.data, filename + '.xlsx')
}
}).catch(() => {
this.$message.error('数据导出失败,请稍后重试!')
})
}