当前位置:   article > 正文

PDF预览和下载(Springboot+Vue+Axios)_移动端vue+springboot 预览pdf responsetype=blob

移动端vue+springboot 预览pdf responsetype=blob

大致流程

后端传数据流,前端已Blob的形式接收,Blob转化成URL直接在浏览器打开。

Vue

两种形式:①直接在浏览器打开URL,打开后可以在PDF里面下载;②直接下载PDF

    private async handleInfo(row: any) {
      const { data,headers } = await read(row.name);
      console.log(headers)
      const url = window.URL.createObjectURL(
        new Blob([data], {
          type: "application/pdf;charset=UTF-8;"
        })
      );
      const link = document.createElement("a");
      link.href = url;
      // 下载的代码
      // link.setAttribute("download", 'test');
      // document.body.appendChild(link);
      // link.click();
      // document.body.removeChild(link);
      window.open(url); // 直接打开预览的代码
      setTimeout(() => {
        this.loading = false;
      }, 0.5 * 1000);
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

API

文件以Blob的形式接收

export const readPDF =(name: string) =>
  request({
    url: `/api/file/readPDF/${name}`,
    responseType: 'blob'
  });
  • 1
  • 2
  • 3
  • 4
  • 5

Service.java

void readPDF(Integer id, HttpServletResponse response) throws IOException();
  • 1

ServiceImpl.java

 public void readPDF(Integer id, HttpServletResponse response) throws IOException { // 预览/下载PDF文件
        String filename = URLEncoder.encode("PDF" ,"UTF-8");
        response.setContentType("application/pdf");
        response.setHeader("filename",""+ filename + ".pdf");
        response.addHeader("Access-Control-Expose-Headers", "filename");

       // 获取数据库中的二进制数据
        QueryWrapper<File> queryWrapper = new QueryWrapper<File>() //利用mybatisPlus按id查询
                .eq("id",id);
        File file = fileMapper.selectOne(queryWrapper);
     
        ByteArrayInputStream in = new ByteArrayInputStream(file.getData());
        OutputStream out = response.getOutputStream();
        byte[] bytes = new byte[1024];
        while((in.read(bytes)) != -1) {
            out.write(bytes);
        }
        out.flush();
        in.close();
        out.close();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Controller.java

application/octet-stream:以二进制流的方式传输文件,只能传输一个。

 @GetMapping(
            value = "/getPDF/{id}",
            produces = {"application/octet-stream;charset=UTF-8"}
    )
    public void readPDF(@PathVariable Integer id, HttpServletResponse response) throws IOException {
       fileService.read(id,response);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/500814
推荐阅读
相关标签
  

闽ICP备14008679号