**PDFjs 文件流在线预览**

最近在做springboot项目 获取sftp文件,在页面预览pdf,参考了很多别人写的,最后简单的实现了在线预览pdf,所需资源放在文章末尾。

1.提取sftp文件,返回byte字节,service层

public byte[] download(String filePath, String fileName) {
        InputStream in = null;
        try {
            ChannelSftp sftp = connect();
            logger.info("文件路径" + filePath);
            sftp.cd(filePath);
            in = sftp.get(fileName);
            byte[] buff = new byte[100];
            int rc = 0;
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            while ((rc = in.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] in2b = swapStream.toByteArray();
            disConnect(sftp);
            return in2b;
        } catch (Exception e) {
            if (logger.isInfoEnabled()) {
                logger.info("文件下载出现异常,[{}]", e);
            }
            throw new RuntimeException("文件下载出现异常,[{}]", e);
        } finally {
            closeStream(in,null
            );
        }
    }

2.字节存放到输出流,service层

 public void previewWithOutPut( byte buffBytes[],HttpServletResponse response){
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/pdf;charset=utf-8");
        OutputStream out = null;
        InputStream is = new ByteArrayInputStream(buffBytes);
        try {
            out = response.getOutputStream();
            int read = 0;
            while ((read = is.read(buffBytes)) != -1) {
                out.write(buffBytes, 0, read);
            }
            out.flush();
            out.close();
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.将在sftp中获取到的字节写入输入流,service层

@Override
    public void preview(String fileId, HttpServletResponse response) {
        AttachmentFile attachmentFile = this.getById(Long.parseLong(fileId));
        String fileName = attachmentFile.getAttachmentFileName()+"."+attachmentFile.getFileType();
        byte buffBytes[] =  sftpService.download(attachmentFile.getFilePath(),fileName);
        previewWithOutPut(buffBytes,response);
    }

4.定义前台调用方法,controller层

@RequestMapping(value = "/preview.pdf")
    @ResponseBody
    public void preview(String fileId,HttpServletResponse response){
        service.preview(fileId, response);
    }

5.前台页面需要先引入pdfjs,资源会放在文章末尾

存放在static目录下

6.页面预览

在这里插入图片描述

这里拼接pdfUrl,这种的是直接文件流的形式预览,无需修改js文件,后面需要传递什么参数可以添加到url路径后面,后台接收即可。
在这里插入图片描述

pdf资源

https://pan.baidu.com/s/1wqKV8bwR5T0rOg-Uv3FzBQ
提取码:ngtp
解压即可

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值