原因:本来是前端直接用url 显示pdf、但是url 容易暴露。
后来使用后台返回文件流的形式输出、前端显示、不多说直接上代码
1、文件存在服务器本地
@RequestMapping(value = "/preview", method = RequestMethod.GET)
public void pdfStreamHandler(HttpServletRequest request, HttpServletResponse response) {
//PDF文件地址
File file = new File("D:\\123.pdf");
if (file.exists()) {
byte[] data = null;
FileInputStream input=null;
try {
input= new FileInputStream(file);
data = new byte[input.available()];
input.read(data);
response.getOutputStream().write(data);
} catch (Exception e) {
System.out.println("pdf文件处理异常:" + e);
}finally{
try {
if(input!=null){
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2、文件存在远程通过url 可以直接打开的那种
@GetMapping("getPdfView")
@ApiOperation(value = "PDF预览")
public void getPdfView(HttpServletRequest request, HttpServletResponse response){
BufferedInputStream in = null;
String remoteFileUrl = "String remoteFileUrl = "http://10.0.5.38/image/download2/node1/2021/06/25/10/12115030882021-06-254772444994050582221.pdf";";
try {
BossPspData bossPspData = pspService.selectByPrimaryKey(id);
if (null == remoteFileUrl || remoteFileUrl.length() == 0) {
throw new RuntimeException("remoteFileUrl is invalid!");
}
URL url = new URL(remoteFileUrl);
byte[] data = null;
in = new BufferedInputStream(url.openStream());
int i;
while ((i = in.read()) != -1) {
response.getOutputStream().write(i);
}
in.close();
response.getOutputStream().close();
}catch (Exception ex){
ex.printStackTrace();
}finally {
try {
if(in!=null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}