Shaun Abram
Technology and Leadership Blog
SpringMVC file download
This post shows how to download a file using Spring MVC. For example, you have a SpringMVC web app and you want to include a link on a page that downloads a file to be opened on the user’s machine (e.g. a Microsoft Excel).
The code is as follows:
@RequestMapping(value = "/Excel", method = RequestMethod.GET)
public void handleFileDownload(HttpServletResponse res) {
try {
String fn = "/Test.xls";
URL url = getClass().getResource(fn);
File f = new File(url.toURI());
System.out.println("Loading file "+fn+"("+f.getAbsolutePath()+")");
if (f.exists()) {
res.setContentType("application/xls");
res.setContentLength(new Long(f.length()).intValue());
res.setHeader("Content-Disposition", "attachment; filename=Test.xls");
FileCopyUtils.copy(new FileInputStream(f), res.getOutputStream());
} else {
System.out.println("File"+fn+"("+f.getAbsolutePath()+") does not exist");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Where:
- “/Excel” is an arbitrary path name (can be anything)
- “Test.xls” resides in src/main/resources
The code uses Spring’s own FileCopyUtils for making the file available.
The complete maven project can be found here on github.
(Previously I had the code deployed on a CloudBees instance at http://springmvc-filedownload.shaunabram.cloudbees.net, but CloudBees have since unfortunately shut down their free tier)