Last active
December 28, 2015 23:09
-
-
Save yanhua365/7577152 to your computer and use it in GitHub Desktop.
Spring MVC 提供文件下载的控制器
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RequestMapping(value = "/download/{filename:.+}", method = RequestMethod.GET) | |
public void download(@PathVariable("filename") String filename,HttpServletRequest request ,HttpServletResponse response){ | |
try { | |
File file=new File(request.getSession().getServletContext().getRealPath("/download/"+filename)); | |
response.setCharacterEncoding("utf-8"); | |
response.setContentType("multipart/form-data"); | |
response.setHeader("Content-Disposition", "attachment;filename="+ filename); | |
response.setHeader("Content-Length", "" + file.length()); | |
//System.out.println(file.getAbsolutePath()); | |
InputStream in = new BufferedInputStream(new FileInputStream(file)); | |
OutputStream out=response.getOutputStream(); | |
byte[] b=new byte[1024]; | |
int length; | |
while((length=in.read(b)) != -1){ | |
out.write(b, 0, length); | |
} | |
in.close(); | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} |
中文文件名未测试。
How To Download File From Website- Java / Jsp
http://www.mkyong.com/java/how-to-download-file-from-website-java-jsp/
我想问下 你下载的文件是放在 download 这个文件夹里麽? 这个文件夹是建立在项目下哪里啊?求解。谢谢
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
{filename:.+} 这个表达式是为了避免文件名中有"."符号的时候,Spring MVC取不到点后面的扩展名。参考:http://stackoverflow.com/questions/16332092/spring-mvc-pathvariable-with-dot-is-getting-truncated ,
http://stackoverflow.com/questions/3526523/spring-mvc-pathvariable-getting-truncated,
http://blog.csdn.net/milife2013/article/details/8059535