原創 前端實戰項目積累小知識(10):vue--前端接收後臺傳過來的excel文件數據

vue--前端接收後臺傳過來的excel文件數據

最近項目要實現把前端展示的列表導出功能,但是接口是post請求,無奈之前做的get請求不能複用。上網開了一下帖子基本是用blob實現下載,以下是我的代碼:

index.vue

         
api.pageCzZlxx(params).then((res) => {
          var blob = new Blob([res], { type: 'application/vnd.ms-excel' }) // type這裏表示xlsx類型
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) // 創建下載的鏈接
          downloadElement.href = href
          downloadElement.download = '出賬申請列表.xls' // 下載後文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 點擊下載
          document.body.removeChild(downloadElement) // 下載完成移除元素
})

我這裏後臺直接再res裏返回,所以不需要res.data獲取 

request.js

service.interceptors.request.use(config => { // 配置axios請求攔截器
  const token = sessionStorage.getItem('token')

  if (token) {
    config.headers = {
      'token': token, // 在請求頭中添加token參數Auth-Code
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' // 在請求頭中添加其它參數
    }
  } else {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8' // 在請求頭中添加其它參數
  }
  console.log(config, 'config')

  if (config.data && config.data._requestType) {
    config.headers['Content-Type'] = 'application/json'
  } else {
    config.data = qs.stringify(config.data)
  }
  if (config.data && (config.data.exportData == 3 || config.data.exportData == 1)) {
    config['responseType'] = 'blob' // 在請求頭中添加其它參數   看清楚一定要把responseType跟headers同層級
  }

  return config
}, error => {
  console.log(error)

  return Promise.reject(error) // 返回一個帶有拒絕reason的Promise請求
})

在請求頭中添加其它參數   看清楚一定要把responseType:‘blob’跟headers同層級。

看到返回這個的時候就說明請求成功。我這裏導出excel,所以傳type: "application/vnd.ms-excel"

親測可以,順便記錄下,也希望能幫助到需要的朋友,如果有什麼不對的地方,望大神在下面指正。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章