在 Vue 項目中,經(jīng)常會遇到下載文件流的情況,使用?new Blob二進制進行文件下載功能(vue后臺返回文件流下載導出函數(shù)封裝、調(diào)用示例),type不同下載的文件格式也不同,這邊本文章下載的是xlsx文件,可根據(jù)自己項目場景更換 new Blob() 的 type 即可
這邊帶大家如何封裝使用(直接C/V就可以用了)文章來源:http://www.zghlxwxcb.cn/news/detail-565701.html
new Blob():?Vue 之 new Blob() 文件流下載文件不同文件類型的 type 值整理_L_羽鵬的博客-CSDN博客文章來源地址http://www.zghlxwxcb.cn/news/detail-565701.html
import axios from 'axios'
const service = axios.create({
// axios中請求配置有baseURL選項,表示請求URL公共部分
baseURL:"http://localhost:3000",
// 超時
timeout:2000
})
// 攔截器
......
......
//導出方法
/*
download(url, params, filename)
第一個參數(shù)是請求的api
第二個參數(shù)是請求參數(shù)
第三個參數(shù)是導出的文件名
*/
export function download(url, params, filename) {
//數(shù)據(jù)請求
return service.post(url, params, {
transformRequest: [(params) => {
return tansParams(params)
}],
// 請求頭
headers: {
'xxx': 'xxx'
},
responseType: 'blob'
}).then((data) => {
const content = data
const blob = new Blob([content], {
// 下載的文件格式自己在這邊更改type的值就好了
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
if ('download' in document.createElement('a')) {
const elink = document.createElement('a')
elink.download = filename
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href)
document.body.removeChild(elink)
} else {
navigator.msSaveBlob(blob, filename)
}
}).catch((r) => {
console.error(r)
})
}
到了這里,關(guān)于vue使用文件流進行下載的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!