处理application/octet-stream格式的文件下载

发布时间 2023-12-19 17:19:51作者: 站住,野猪佩奇

 

export function downloadFile(url, data) {
axios({
  method: 'post',
  url: Vue.prototype.myUrl + url,
  headers: {
    'x-auth-token': window.localStorage.getItem('token')
  },
  responseType: 'blob',
  data: data
}).then((res) => {
  if (res.data) {
    var blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
    })
    var downloadElement = document.createElement('a')
    var href = window.URL.createObjectURL(blob) // 创建下载的链接
    downloadElement.href = href
    downloadElement.download = decodeURI(res.headers.attachment) // 下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() // 点击下载
    document.body.removeChild(downloadElement) // 下载完成移除元素
    window.URL.revokeObjectURL(href)
  }
}).catch((res) => {
    Message({
      message: res.message,
      type: 'error',
      duration: 5 * 1000
    })
  })
}