Spring MVC返回pdf文件并在页面显示而不是下载
spring mvc下载pdf
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// 读取pdf文件到字节里
Path path = Paths.get("path/to/file");
byte[] contents = Files.readAllBytes(path);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "output.pdf";
headers.setContentDispositionFormData("attachment", filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return response;
}
如果上面的代码变为下载,可以尝试
headers.setContentDispositionFormData("inline", fileName);
或
headers.add("content-disposition", "inline;filename=" + fileName)
浏览器会尝试把inline的内容显示在页面。
如果有中文乱码问题:
headers.setContentDispositionFormData("attachment", new String(filename.getBytes("utf-8"), "ISO8859-1"));