前提SSM框架,略过……直接上代码,如下: @RequestMapping("/fileDownLoad") public void fileDownLoad(HttpServletRequest request, HttpServletResponse response, int id) throws Exception{ ServletContext servletContext = request.getServletContext(); String realPath = servletContext.getRealPath("/WEB-INF/upload"); String fileRealPath = makeFilePath("学习笔记.docx", realPath); download("学习笔记.docx",fileRealPath,response); }
private String makeFilePath(String fileName, String path) { //int hashCode = fileName.hashCode(); String dir = path +"\\"+ fileName; return dir; } public void download(String fileName, String filePath, HttpServletResponse response) throws Exception { String filename = fileName; response.reset(); response.setCharacterEncoding("UTF-8"); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String agent = request.getHeader("User-Agent"); boolean isMSIE = agent != null && agent.indexOf("MSIE") != -1 || agent != null && agent.indexOf("Trident") != -1; if (isMSIE) { filename = URLEncoder.encode(filename, "UTF-8"); } else { filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); } response.setHeader("Content-Disposition", "attachment;filename=" + filename); response.setContentType("application/msexcel"); InputStream fis = new BufferedInputStream(new FileInputStream(filePath)); OutputStream os = new BufferedOutputStream(response.getOutputStream()); byte[] b = new byte[1000]; int len; while((len = fis.read(b)) > 0) { os.write(b, 0, len); } os.flush(); os.close(); fis.close(); }
文件存储位置如下图,如在服务器端,filepath更改为自己存储的位置即可!