首页 > 其他分享 >vue通过Blob数据类型导出文件

vue通过Blob数据类型导出文件

时间:2022-09-27 17:56:34浏览次数:49  
标签:vue url 数据类型 link Blob data method blob

适用于pc端和移动端:

公共方法:

 

 1 // 通过后端接口拿到文件流
 2 export function downloadFile(url, parameter, method) {
 3   return request({
 4     url: url,
 5     method: method || 'post',
 6     data: method !== 'get' ? parameter : null,
 7     params: method === 'get' ? parameter : null,
 8     responseType: 'blob' // 这一行是关键,拿到blob数据类型的文件
 9   })
10 }

 

业务中调用:

 1     // 导出报告:
 2     exportReport() {
 3       downloadFile(url, param, 'get').then(data => {
 4         // 拿到 blob 数据类型
 5         this.exportFile(data, 文件标题, '.docx')
 6       })
 7     },
 8 
 9     exportFile(data, fileName, fileSuffix) { 
10       let blob = window.URL.createObjectURL(new Blob([data]))
11       let link = document.createElement('a')
12       link.style.display = 'none'
13       link.href = blob
14       link.setAttribute('download', fileName + fileSuffix) // fileSuffix是文件后缀名
15       document.body.appendChild(link)
16       link.click()
17       document.body.removeChild(link) //下载完成移除元素
18       window.URL.revokeObjectURL(blob) //释放掉 blob 对象
19     },

 

标签:vue,url,数据类型,link,Blob,data,method,blob
From: https://www.cnblogs.com/buluzombie/p/16735403.html

相关文章