springMVC以附件形式下载PDF文件(解决了下载后文件格式出错无法打开的问题)
公司的上网行为管理系统项目有一个功能模块是统计报表,今天在完成这个功能的过程中碰到一个需求:将服务器上的PDF文件以附件的形式下载到本地。
马上想起springMVC提供了文件下载的功能,非常开心。然而,不碰上点bug不足以写博客啊!
先贴完整代码:
public ResponseEntity<byte[]> download(String fileName)throws Exception{
String filePath= ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/static/images/");
File file=new File(filePath +File.separator+ fileName);
org.springframework.http.HttpHeaders headers=new org.springframework.http.HttpHeaders();
//解决中文乱码
String downloadFileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
//文件名设置UTF-8编码,并以附件形式下载
headers.setContentDispositionFormData("attachment", downloadFileName);
//以PDF文件格式下载
headers.setContentType((MediaType.parseMediaType("application/pdf")));
r