1. 程式人生 > 程式設計 >vue-以檔案流-blob-的形式-下載-匯出檔案操作

vue-以檔案流-blob-的形式-下載-匯出檔案操作

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,{ 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)
 }
}

總結:至此,以檔案流的形式匯出檔案的一種方式便已經實現。

補充知識:vue中使用檔案流進行下載(new Blob),不開啟一個新頁面下載

我就廢話不多說了,大家還是直接看程式碼吧~

export function download (url,params,filename) {
 
 Message.warning('匯出資料中')
 return axios.get(url,{
  params: params,responseType:'arraybuffer',}).then((r) => {
 
  const content = r.data
  const blob = new Blob([content],{type:'application/vnd.ms-excel'})
  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)
   Message.success('匯出成功')
 
  }
 
 }).catch((r) => {
  console.error(r)
  Message.error('匯出失敗')
 
 })
}

以上這篇vue-以檔案流-blob-的形式-下載-匯出檔案操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。