欢迎大家来到IT世界,在知识的湖畔探索吧!
在SpringMVC的开发过程中,有时需要实现文档的下载功能。word,excel,pdf作为大家最常用的办公程序,它的文件传输就显得尤为重要,本文通过使用spring 提供的Resource封装来实现实现word/xlsx/pdf文件下载功能。话不多说。
o
package com.davidwang456;import java.io.File;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.core.io.FileSystemResource;import org.springframework.core.io.Resource;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class DownloadController { private static final String APPLICATION_PDF="application/pfd"; private static final String APPLICATION_WORD="application/msword"; private static final String APPLICATION_EXCEL="application/vnd.ms-excel;charset=utf-8"; @RequestMapping(value="/download",method=RequestMethod.GET,produces=APPLICATION_PDF) @ResponseBody public Resource download(HttpServletRequest req,HttpServletResponse resp) { String fileName=req.getParameter("file"); File file=getFile(fileName); String suffix=fileName.substring(fileName.lastIndexOf(".")+1); if(suffix.equalsIgnoreCase(APPLICATION_PDF)) { resp.setContentType(APPLICATION_PDF); resp.setHeader("Content-Disposition", "inline;filename="+file.getName()); }else if(suffix.equalsIgnoreCase(APPLICATION_WORD)) { resp.setContentType(APPLICATION_WORD); resp.setHeader("Content-Disposition", "attachment;filename="+file.getName()); }else if(suffix.equalsIgnoreCase(APPLICATION_EXCEL)) { resp.setContentType(APPLICATION_EXCEL); resp.setHeader("Content-Disposition", "attachment;filename="+file.getName()); } resp.setHeader("Content-Length", String.valueOf(file.length())); return new FileSystemResource(file); } private static File getFile(String fileName) { File file=new File( "path"+fileName); if(!file.exists()) { System.out.println("指定路径下的文件不存在!"); } return file; }}
欢迎大家来到IT世界,在知识的湖畔探索吧!
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/34575.html