[問題探討]VUE項目下載excel,通過window.open可以下載,通過axios+blob下載的文件亂碼

背景:

VUE項目,下載excel需求,通過window.open可以正常下載正常顯示,通過axios+blob下載的文件亂碼

前端代碼:

1,axios部分(request.js)

const service = axios.create({
  timeout: 25000 // request timeout
})
......省略其他

2,頁面API部分

import request from '@/utils/request'
// 導出
export function excel(param) {
  return request({
    url: '/dangerous/excel?attributesPath=' + param.attributesPath + '&tjDate=' + param.tjDate,
    method: 'get'
  })
}

3,blob部分

	import { excel } from '@/api/dangerousVehicleDailyReport'
	.......省略其他
      excel(param).then((res) => {
        const blob = new Blob([res.data])
        const fileName = '危險品車輛日報表.xlsx'
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(blob, fileName)
        } else {
          const elink = document.createElement('a')
          document.body.appendChild(elink)
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          elink.click()
          elink.remove()
          URL.revokeObjectURL(elink.href)
        }
      }).catch((error) => {
        console.log(error)
      })

解決辦法:

修改request配置,增加responseType: ‘blob’

import request from '@/utils/request'
// 導出
export function excel(param) {
  return requestForBlob({
    url: '/dangerous/excel?attributesPath=' + param.attributesPath + '&tjDate=' + param.tjDate,
    method: 'get',
    responseType: 'blob'
  })
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章