后端给前端传response下载excel文件

功能背景:

项目中使用vue作为框架,以axios方式来发送post请求,后台返回了一个包含了excel文件流的response。

遇到的问题:

调用了接口之后,不报错也不进行下载

遇到问题的原因:

是由于ajax请求只是一个字符型的请求,但是文件是以二进制进行传输的,ajax无法解析后台返回的文件流,因此,调用无反应。

解决:

在调用下载接口的时候,规定responseType:‘blob’,表示后台传来的数据用blob对象接收

以下是解决之后的前端代码

exportExcel(ids){
      if (ids instanceof Array && ids.length < 1) {
        this.$notification.error({
          message: "请选择要导出的数据!",
        });
        return;
      }
      let formData = new FormData();
      formData.append("ids",ids)
      axios({ // 用axios发送post请求
          method: 'post',
          url: api.exportDictionaryExcel(), // 请求地址
          data: formData, // 参数
          responseType: 'blob' // 表明返回服务器返回的数据类型
        })
          .then((res) => { // 处理返回的文件流
            const content = res
            const blob = new Blob([content])
            console.log(content)
            const fileName = 'xxx.xlsx'
            if ('download' in document.createElement('a')) { // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
            } else { // IE10+下载
              navigator.msSaveBlob(blob, fileName)
            }
        })
    },

以下是解决之后的后端代码

public static void download(Workbook wb, HttpServletResponse response, String returnName) throws IOException{
        response.setContentType("application/octet-stream;charset=UTF-8");
        // 保存的文件名,必须和页面编码一致,否则乱码
        returnName = URLEncoder.encode(returnName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + returnName);
        wb.write(response.getOutputStream());
    }

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值