axios下载文件

1. axios端

  • 发送请求
  • 获得response流文件
  • 如果是文件则在页面中插入a标签
  • 利用a标签实现浏览器的get下载
      instance.get('url',{
        params: {
          path: 'xxx'
        },
        responseType: 'blob'
      }).then(res => {
        const { data, headers } = res
        const fileName = headers['Content-Disposition'].replace(/\w+;filename=(.*)/, '$1')
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName );
        document.body.appendChild(link);
        link.click();
      });

2. java端response暴露请求头Content-Disposition,方便前端获取

// 设置输出的格式
httpServletResponse.reset();
httpServletResponse.setContentType("application/octet-stream");
httpServletResponse.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("gbk"),"iso8859-1"));

3. 前端兼容方案

          let blob = new Blob([response.data]);//response.data为后端传的流文件
          let downloadFilename = xxx.docx;//设置导出的文件名
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            //兼容ie浏览器
            window.navigator.msSaveOrOpenBlob(blob, downloadFilename)
          }else {
            //谷歌,火狐等浏览器
            let url = window.URL.createObjectURL(blob);
            let downloadElement = document.createElement("a");
            downloadElement.style.display = "none";
            downloadElement.href = url;
            downloadElement.download = downloadFilename;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement);
            window.URL.revokeObjectURL(url);
          }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值