最近在做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,资源会放在文章末尾
6.页面预览
这里拼接pdfUrl,这种的是直接文件流的形式预览,无需修改js文件,后面需要传递什么参数可以添加到url路径后面,后台接收即可。
pdf资源
https://pan.baidu.com/s/1wqKV8bwR5T0rOg-Uv3FzBQ
提取码:ngtp
解压即可