axios通过pdf下载地址预览pdf

前言

最近做一个功能,根据一个pdf的下载地址,做出既能下载又能预览pdf的两个功能按钮,因为地址本身在浏览器中打开就能下载,直接记录怎么实现预览功能。

具体步骤

1.前台html代码

<iframe id="iframe" frameborder="0" style="width: 100%; height: 100%"></iframe>

2.前台js代码

axios({
  method: 'get',
  url:'/preview', 
  params:{
       pdfUrl:'https://xxxx/xxx/xxx.pdf'
  },
  responseType: 'blob',
}).then(function (response) {
  let blob = new Blob([response.data], { type: response.data.type })
  let url = URL.createObjectURL(blob)
  document.getElementById('iframe').src = url
}).catch(err => {
});

3.后台代码

 	@RequestMapping("/preview")
    public void preview(HttpServletResponse response, String pdfUrl) {
        response.setContentType("application/pdf");
        try(OutputStream out = response.getOutputStream();
            InputStream in = new BufferedInputStream(new URL(pdfUrl).openConnection().getInputStream())) {
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = in.read(b))!=-1) {
                out.write(b,0,len);
            }
            out.flush();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

后记

实现办法还有用pdf.js,因为不想在vue中添加依赖,没有采用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值