element获取后端数据流实现PDF文件的预览(开发小记)

10 篇文章 0 订阅
2 篇文章 0 订阅

后端代码:

/**
     * @param response
     * @param archiveId 文件id
     * @param openStyle = inline 预览  =attachment 下载
     * @throws Exception
     */
    @GetMapping("arcDownload")
    public void arcDownload(HttpServletResponse response, String archiveId, String openStyle) throws Exception {
        // 文件地址,真实环境是存放在数据库中的
        String fileName = "";
        //获取打开方式
        openStyle = openStyle == null ? "attachment" : openStyle;
        //获取文件信息
        BusArchives archives = busArchivesService.getById(archiveId);
        File file = new File(archives.getFilePath());
        // 穿件输入对象
        FileInputStream fis = new FileInputStream(file);

        // 设置相关格式
        //HttpHeaders headers = new HttpHeaders();
        //response.setContentType("application/"+archives.getFileType());
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        // 设置下载后的文件名以及header
        response.addHeader("Content-Disposition", openStyle + ";fileName=" + java.net.URLEncoder.encode(archives.getFileName(), "UTF-8"));
        // 创建输出对象
        OutputStream os = response.getOutputStream();
        // 常规操作
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        fis.close();
    }

element JS代码:

/**
   * PDF预览
   * @param params
   * @returns {AxiosPromise}
   */
  arcDownloadPDF(params){
    return request({
      url: "/bus-archives/arcDownload",
      method: "get",
      params,
      responseType:'blob',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}

    })
  },

element请求:

preview(id) {
        $.arcDownloadPDF({archiveId: id, openStyle: "inline"}).then(res => {
          console.log(res.data)
          let blob = new Blob([res.data], {
            type: "application/pdf;charset=gbk"
          });
          let fileName = decodeURI(
            res.headers["content-disposition"].split("=")[1]
          );
          var link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          // link.click(); //这里是下载
          window.open(link); //这里是预览
          console.log(link)
        })
      },

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值