vue項目中,經常遇到文件導出與下載,有時候是直接返回服務端的文件url,這樣直接以a鏈接下載,或者windown.open對不同類型的文件進行下載或預覽。但如果返回的是文件流,則需要做一些其他處理,具體形式如下:
1、首先要確定服務器返回的數據類型。
在請求頭中加入: config.responseType = 'blob'
有時候,不是所有接口都需要該類型,則可以對接口做一個判定:
// request攔截器 service.interceptors.request.use( config => {
// 根據接口判定 if ( config.url === '/setting/exportData' || config.url.indexOf('export') > -1 || config.url.indexOf('Export') > -1) { config.responseType = 'blob' // 服務請求類型 } if (getToken()) { config.headers['access_token'] = getToken() } return config }, error => { // Do something with request error // console.log(error) // for debug Promise.reject(error) } )
2、接口請求獲取后端返回的文件流
// 導出 onExport() { if (this.dataList === '') { this.$message({ type: 'error', message: '暫無數據導出' }) return } const fd = new FormData() fd.append('id', this.id) var exportFileName = '導出文件名' //設置導出的文件名,可以拼接一個隨機值 exportData(fd) .then(res => { // res.data 是后端返回的文件流 // 調用 downloadUrl 處理文件 downloadUrl(res.data, exportFileName) }) .catch(err => { this.$message({ type: 'error', message: err.message }) }) },
3、文件處理downloadUrl--該方法可以寫為公共方法以便調用
// 使用iframe框架下載文件--以excel為例,可修改type與fileName選擇文件類型 export function downloadUrl(res, name) { const blob = new Blob([res], { type: 'application/vnd.ms-excel' }) // 構造一個blob對象來處理數據 const fileName = name + '.xlsx' // 導出文件名 const elink = document.createElement('a') // 創建a標簽 elink.download = fileName // a標簽添加屬性 elink.style.display = 'none' elink.href = URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() // 執行下載 URL.revokeObjectURL(elink.href) // 釋放URL 對象 document.body.removeChild(elink) // 釋放標簽 }
4、在ie瀏覽器中存在兼容性問題,對downloadUrl做一些調整
// 使用iframe框架下載文件 -兼容性考慮 export function downloadUrl(res, name) { const blob = new Blob([res], { type: 'application/vnd.ms-excel' }) // for IE if (window.navigator && window.navigator.msSaveOrOpenBlob) { const fileName = name + '.xlsx' window.navigator.msSaveOrOpenBlob(blob, fileName) } else { // for Non-IE (chrome, firefox etc.) const fileName = name + '.xlsx' 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) } }
總結:至此,以文件流的形式導出文件的一種方式便已經實現。
