vue实现blob文档流下载文件

在这里简单的记录下vue如何实现blob文档流下载文件,通过调用后端接口或返回一个很乱的数据

如下图

注意:在这里需要特别注意的是不管接口是get还是post请求,在请求时需要多加一个参数 responseType:'blob' ,否则等等下载的文件会出现乱码

常见的axios请求如下:

//post请求
axios.post(url, {...params}, {responseType: 'blob'}).then((res) => {
				
			}).catch((err) => {
				
			})

//get请求
axios.get(url, {params: {}, responseType: 'blob'}).then((res) => {
	
}).catch((err) => {
	
})

如果是封装后的axios,对应的在请求时添加

以下为接口成功回调后的操作

//下载
downLoad() {
    // 原生请求可替换成对应封装后请求成功的回调中进行处理
		axios.post(url, {...params}, {responseType: 'blob'}).then((res) => {
			const blob = new Blob([res.data])//返回一个新的blob对象
			let fileName = '模版.xls'//下载文件名
			const downLoadElement = document.createElement('a')//创建a标签
			downLoadElement.style.display = 'none'//a标签样式为隐藏
			const href = window.URL.createObjectURL(blob)//创建window临时地址
			downLoadElement.href = href//跳转地址
			downLoadElement.setAttribute('download', fileName)
			document.body.appendChild(downLoadElement)//将指定的dom添加的body之后
			downLoadElement.click()//点击事件
			document.body.removeChild(downLoadElement)//移除dom
			window.URL.revokeObjectURL(href)//释放url地址
		}).catch((err) => {

	})
			
},

猜你喜欢

转载自blog.csdn.net/A1123352950/article/details/134517068
今日推荐