This tutorial shows you the Spring MVC Download File Example by using HttpServletResponse, HttpEntity and Spring FileSystemResource. So you can either download a file as an attachment or directly view it inside the browser.
Table of contents:
1. Maven Dependencies
2. Project Structure
3. Three ways to download file
4. Spring MVC Download File Controller
5. Exception handling
6. Download View
6. Deploy Spring MVC Download File Example
Other interesting posts you may like
Maven Dependencies
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javabycode.spring.mvc</groupId> <artifactId>download-file-example</artifactId> <version>1.0.0-SNAPSHOT</version> <name>SPRING-MVC - ${project.artifactId}</name> <url>http://javabycode.com</url> <packaging>war</packaging> <properties> <encoding>UTF-8</encoding> <spring.version>4.3.0.RELEASE</spring.version> </properties> <dependencies> <!-- spring dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- servlet api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>download-file-example</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> |
Project Structure
Three ways to download file
Download File using HttpServletResponse
Firstly, we have to set the header properties like Content-Type, Content-Disposition and Content-Length. The Content-Disposition property instructs the browser which filename is used and whether the the file is downloaded as attachment or displayed in the browser. Secondly, We use the HttpServletResponse to write a file directly to the ServletOutputStream.
The code snippet show you the file is downloaded as an attachment.
1 2 3 4 5 6 7 8 9 10 |
@RequestMapping(value = "/servlet", method = RequestMethod.GET, produces = APPLICATION_PDF) public @ResponseBody void downloadByServlet(HttpServletResponse res) throws IOException { File file = getFile(); InputStream in = new FileInputStream(file); res.setContentType(APPLICATION_PDF); res.setHeader("Content-Disposition", "attachment; filename=" + file.getName()); res.setHeader("Content-Length", String.valueOf(file.length())); FileCopyUtils.copy(in, res.getOutputStream()); } |
Download File using HttpEntity
The HttpEntity is used to download file also. And we set the headers like Content-Type, Content-Disposition and Content-Length. But we instruct the browser to display the file by using inline here (if the file type is supported by browser).
1 2 3 4 5 6 7 8 9 10 11 12 |
@RequestMapping(value = "/entity", method = RequestMethod.GET, produces = APPLICATION_PDF) public @ResponseBody HttpEntity<byte[]> downloadByEntity() throws IOException { File file = getFile(); byte[] document = FileCopyUtils.copyToByteArray(file); HttpHeaders header = new HttpHeaders(); header.setContentType(new MediaType("application", "pdf")); header.set("Content-Disposition", "inline; filename=" + file.getName()); header.setContentLength(document.length); return new HttpEntity<byte[]>(document, header); } |
Download File using Resource
We can use the FileSystemResource of Spring MVC that helps to manage the streams. Beside, Spring also supports many implementations of the Resource class, ClassPathResource and UrlResource for example.
1 2 3 4 5 6 7 8 |
@RequestMapping(value = "/resource", method = RequestMethod.GET, produces = APPLICATION_PDF) public @ResponseBody Resource downloadByResource(HttpServletResponse res) throws FileNotFoundException { File file = getFile(); res.setContentType(APPLICATION_PDF); res.setHeader("Content-Disposition", "inline; filename=" + file.getName()); res.setHeader("Content-Length", String.valueOf(file.length())); return new FileSystemResource(file); } |
Spring MVC Download File Controller
Here, we implement a Spring MVC controller (MyDownloadController for example) to download a file using three ways above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
package com.javabycode.controller; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @Controller @RequestMapping("/download") public class MyDownloadController { private static final String FILE_PATH = "C:/tmp/Fruit-Category.pdf"; private static final String APPLICATION_PDF = "application/pdf"; @RequestMapping(value = "/servlet", method = RequestMethod.GET, produces = APPLICATION_PDF) public @ResponseBody void downloadByServlet(HttpServletResponse res) throws IOException { File file = getFile(); InputStream in = new FileInputStream(file); res.setContentType(APPLICATION_PDF); res.setHeader("Content-Disposition", "attachment; filename=" + file.getName()); res.setHeader("Content-Length", String.valueOf(file.length())); FileCopyUtils.copy(in, res.getOutputStream()); } @RequestMapping(value = "/entity", method = RequestMethod.GET, produces = APPLICATION_PDF) public @ResponseBody HttpEntity<byte[]> downloadByEntity() throws IOException { File file = getFile(); byte[] document = FileCopyUtils.copyToByteArray(file); HttpHeaders header = new HttpHeaders(); header.setContentType(new MediaType("application", "pdf")); header.set("Content-Disposition", "inline; filename=" + file.getName()); header.setContentLength(document.length); return new HttpEntity<byte[]>(document, header); } @RequestMapping(value = "/resource", method = RequestMethod.GET, produces = APPLICATION_PDF) public @ResponseBody Resource downloadByResource(HttpServletResponse res) throws FileNotFoundException { File file = getFile(); res.setContentType(APPLICATION_PDF); res.setHeader("Content-Disposition", "inline; filename=" + file.getName()); res.setHeader("Content-Length", String.valueOf(file.length())); return new FileSystemResource(file); } private File getFile() throws FileNotFoundException { File file = new File(FILE_PATH); if (!file.exists()){ throw new FileNotFoundException(" File not found with path: " + FILE_PATH + "."); } return file; } } |
Exception handling
The exception processing is necessary while working with a file. The exception can be thrown such as FileNotFoundException, IOException and so so. In this tutorial, we will handle two exceptions by annotating the MyExceptionHandler class with @ControllerAdvice. And the @ExceptionHandler annotation in conjunction with the specified exception are annotated with the appropriate methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.javabycode.exception; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import javax.servlet.http.HttpServletResponse; import java.io.FileNotFoundException; import java.io.IOException; @ControllerAdvice public class MyExceptionHandler { @ExceptionHandler(value = FileNotFoundException.class) public void handleFileNotFound(FileNotFoundException ex, HttpServletResponse res) throws IOException { System.out.println("Handling file not found exception"); res.sendError(404, ex.getMessage()); } @ExceptionHandler(value = IOException.class) public void handleIOExcpeption(IOException ex, HttpServletResponse res) throws IOException { System.out.println("Handling io exception"); res.sendError(500, ex.getMessage()); } } |
Download View
Now, we create the view to demonstrate the Spring MVC Download File Example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>3 Ways to download file using Spring MVC</title> </head> <body> <h1>3 Ways to download file using Spring MVC</h1> <li><a href="<c:url value='/download/servlet'/>">Click me to download file using servlet response.</a><br/></li> <li><a href="<c:url value='/download/entity'/>">Click me to download file using http entity.</a><br/></li> <li><a href="<c:url value='/download/resource'/>">Click me to download file using file system resource.</a><br/></li> </body> </html> |
Deploy Spring MVC Download File Example
Building project with maven then deploy file war on application server or servlet container (Tomcat 8 for example). Access the address URL http://localhost:8080/download-file-example/ and the screen will display such as the picture
Download the file as an attachment by clicking the link “Click me to download file using servlet response” and the screen shot should be
Download the file as an inline by clicking the link “Click me to download file using http entity.” or “Click me to download file using file system resource.” and the screen shot should be
That’s it on the tutorial Spring MVC Download File Example. If you want to know how to upload a file using Spring MVC, please refer to the link Spring MVC File Upload Validation Example
Download complete source code, please click link below
Spring-MVC-Download-File-Example.zip (450 downloads)
Source code on Github https://github.com/javabycode/spring-mvc-download-file-example