最近项目需要有一个直接在浏览器上查看pdf的接口需要写,给大家分享一下
这是我的一个写的一个Controller层的代码,他是把前端传过来的路径作为File的参数
然后传为流后进行写入response,实现起来相对简单
/**
* 文件在线预览`
*/
@GetMapping(value = "/findFile")
@ResponseBody
public void findContract(String filePath, HttpServletResponse response){
File file=new File(filePath);
if (file.exists()){
byte[] data = null;
try {
FileInputStream input = new FileInputStream(file);
data = new byte[input.available()];
input.read(data);
//这行代码是设置ContentType,把他设置成pdf,不然浏览器访问就会出一大堆看不懂的东西
response.setContentType("application/pdf;charset=UTF-8");
response.getOutputStream().write(data);
input.close();
} catch (Exception e) {
logger.info("pdf处理文件异常"+e);
}
}
}