Loading

axios下载blob文件

1. 接口api

export function downTemplate(data) {
  return request({
    url: 'bridge/bridegaccidentinfo/download',
    method: 'get',
    responseType: "blob", //设置接收数据的类型
    params: data,
  })
}

2.接口调用

// 下载模版
    downTemplate() {
      this.downTemplateLoading = true
      this.downTemplateText = '正在下载模版'
      api
        .downTemplate()
        .then(({ data }) => {
          this.downTemplateLoading = false
          this.downTemplateText = '点击此处下载模版'
          if (data.type == 'application/vnd.ms-excel') {
            const fileName = '事故信息.xlsx' // 导出文件名
            fileLocalDownLoad([data], fileName)
          } else {
            this.$message.error('事故信息模版下载失败')
          }
        })
        .catch((err) => {
          this.downTemplateLoading = false
          this.downTemplateText = '点击此处下载模版'
        })
    },

3. 文件处理utils  ----- fileLocalDownLoad

export function fileLocalDownLoad (data, fileName) {
    const blob = new Blob(data)
    let downloadElement = document.createElement('a')
    let href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = decodeURIComponent(fileName)
    document.body.appendChild(downloadElement)
    downloadElement.click()
    document.body.removeChild(downloadElement)
    window.URL.revokeObjectURL(href)
}

 


posted @ 2021-11-26 09:39  请叫我王小胖  阅读(390)  评论(0编辑  收藏  举报