[前端]导出blob 文件前端方法

标题前言:最近导出文件喜欢用blob的形式,不占用磁盘资源

需要注意的是中文文件名称后端要提前加密,在请求头中传过来.前端再解码拿到

1.前端代码

 exportMethod() {

        var xhr = new XMLHttpRequest(); // 用这种原生请求下载后端返回的二进制流打开就不会出现空白
        xhr.open(
            "get",
            "/download/excel/publicity_list?contest_id="+that.queryParams.contest_id+"&group_id="+that.queryParams.group_id,
            true
        );
        xhr.responseType = "blob";
        xhr.onload = function() {
          that.loading = false;
          const url = window.URL.createObjectURL(this.response);
          const disposition =xhr.getResponseHeader('content-disposition');

          var filename = "";
          var realFileName="";

          if (disposition && disposition.indexOf('inline') !== -1) {
            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            var matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) {
              filename = matches[1].replace(/['"]/g, '');
              realFileName=URLDecoder.decode(filename, "utf-8");
            }
          }

          const link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", realFileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        };
        xhr.send();
      },

2.后端代码

    public void outputMethod(HttpServletResponse response,String filePath){

        ServletOutputStream out = null;
        File file = new File(filePath);
        FileInputStream inputStream=null;
        try{
            out = response.getOutputStream();
            inputStream = new FileInputStream(file);
            if(filePath.contains(".xlsx")){
                //
            /** 导出excel文件流 */
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));
            response.setCharacterEncoding("UTF-8");
            }else{

                /** 导出pdf文件流 */
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/pdf");
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline; filename="+ URLEncoder.encode(file.getName(),"UTF-8"));
            }


            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally{
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.error("输入流关闭失败, {}", e);
            }
            try {
                out.close();
            } catch (IOException e) {
                logger.error("输出流关闭失败, {}", e);
            }
        }
        //删除.xlsx  或    pdf文件
         file.delete();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值