vue导出后端回传的文件流

axios.get() 方法用于发送 GET 请求至后端接口,并将响应数据的 responseType 设置为 ‘blob’,以便正确处理二进制文件。通过 window.URL.createObjectURL() 创建一个临时的下载链接,并使用 元素进行下载操作。然后,通过解析响应头中的 Content-Disposition 头部信息获取文件名,并将链接设置为下载属性。

// 在 Vue 组件中定义一个方法,用于触发下载
methods: {
  downloadFile() {
    // 调用后端接口获取文件路径或者内容
    // 假设后端接口返回一个文件下载链接
    axios.get('/api/download', { responseType: 'blob' })
      .then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;

        // 提取文件名
        const contentDispositionHeader = response.headers['content-disposition'];
        let fileName = 'file';
        if (contentDispositionHeader) {
          const fileNameMatch = contentDispositionHeader.match(/filename="(.+)"/);
          if (fileNameMatch.length >= 2) {
            fileName = fileNameMatch[1];
          }
        }

        // 设置下载文件的属性(名称和类型)
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();

        // 清理创建的临时链接
        URL.revokeObjectURL(url);
      })
      .catch(error => {
        console.error(error);
        // 处理错误
      });
  }
}

使用{responseType: ‘arraybuffer’}也可以正常下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值