vue中下载文件导出保存到本地

vue中下载文件导出保存到本地

先分析如何下载:先有一个链接地址,然后使用 location.hrefwindow.open()下载到本地

看看返回数据
在这里插入图片描述
res.config.url 中是下载链接地址,res.data 中是返回的二进制数据

如何下载

...
<el-button icon="el-icon-download" @click="download(id)"></el-button>
...
download(id) { // 导出
  this.$API({
    name: 'Download',
    paths: [id]
  }).then(res => {
    // window.open(res.config.url, '_self')或者
    window.location.href = res.config.url
  }).catch(error => {
    this.$message({ type: 'error', message: error })
  }).finally(() => {
  })
}

上面情况针对的是后端返回文件流,如果后端返回的是文件名
在这里插入图片描述
通用下载方法

window.location.href = baseURL + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + true

这样就能实现在当前窗口下载文件了

另一种情况

如果下载的文件既可以是txt文件或html文件也可以是压缩包等,对于这种类型的下载处理

    download (row) { // 下载
      this.$API({
        name: 'DownloadResource',
        params: {
          path: row.path,
          token: this.$Cookies.get('token')
        },
        headers: {
          'Content-Type': 'application/octet-stream'
        },
        requireAuth: true
      }).then (res => {
        window.open(`${res.config.url}?path=${res.config.params.path}&token=${res.config.params.token}`, '_self')
      }).catch(error => {
        this.$message.error(error)
      })
    }

对于 headers 中的 'Content-Type': 'application/octet-stream' ,需要在 axios 拦截器中单独处理
建议把 res 打印出来看里面包含的内容

axios.interceptors.response.use(res => {
  // 处理下载文件的接口
  if (res.config.headers['Content-Type'] === 'application/octet-stream') {
    return res
  }
  if (res.data.code) {
    return Promise.resolve(res)
  } else {
    return Promise.reject(res)
  }
}, error => {
  return Promise.reject(error)
})

根据接口返回的url下载pdf文件

pdf的URL直接打开的话是网页预览界面,而不是文件下载,文件下载需要的是二进制数据,但是如果接口返回的是在线链接,那么可以通过以下操作进行格式转化再去下载

import axios from 'axios';
 
methods: {
  async downloadPDF(pdfUrl) {
    const response = await axios({
      url: pdfUrl,
      method: 'GET',
      responseType: 'blob', // 必须指定为blob类型才能下载
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', this.doFormatFileName(pdfUrl));
    document.body.appendChild(link);
    link.click();
  },
},
doFormatFileName(name) {
   if (name) {
     return name?.split('\/')?.at(-1);
   }
   return name;
 },
  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值