Skip to content

Instantly share code, notes, and snippets.

@yanhua365
Last active December 28, 2015 23:09
Show Gist options
  • Save yanhua365/7577152 to your computer and use it in GitHub Desktop.
Save yanhua365/7577152 to your computer and use it in GitHub Desktop.
Spring MVC 提供文件下载的控制器
@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();
}
}
@yanhua365
Copy link
Author

@yanhua365
Copy link
Author

中文文件名未测试。

@yanhua365
Copy link
Author

How To Download File From Website- Java / Jsp
http://www.mkyong.com/java/how-to-download-file-from-website-java-jsp/

@hi-mamba
Copy link

hi-mamba commented Sep 6, 2014

我想问下 你下载的文件是放在 download 这个文件夹里麽? 这个文件夹是建立在项目下哪里啊?求解。谢谢

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment