首先pdf工具类并规定其响应的数据类型 ,否则请求时会出现HttpMediaTypeNotAcceptableException异常,代码如下:
public static void outputPdf( HttpServletResponse response, String fileName) throws IOException{
response.setContentType("*/*");
FileInputStream in = new FileInputStream(new File(fileName));
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
while ((in.read(b))!=-1) {
out.write(b);
}
out.flush();
in.close();
out.close();
}
然后准备Controller 代码如下:
//path为本地文件绝对路径
public R pdfs( HttpServletResponse response,String path){
try {
outputPdf(response,path);
return R.ok();
}catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
return R.error("请求类型错误!");
}
}