File Download in Spring MVC

File Download in Spring MVC

In general, in web applications, it is very frequent operation to perform download operation.

If we want to perform Download operation in Spring WEB MVC Application then we have to use the following steps.

1. Prepare a File with “Download” button and with the downloadable resource.

E.g

downloadpage.jsp

<form method="post" action="download">
   <img alt="JavaImage" src="/home/ashok/Java.jpg" width="200" height="200"/>
   <br>
   <input type="submit" value="Download"/></td>
</form>

2. Prepare Controller class

In Controller class and in action method we have to use the following steps.

a. Set Content Type as “APPLICATION/OCTET-STREAM”.

response.setContentType("APPLICATION/OCTET-STREAM);

b. Set “content-disposition” response header to response object.

response.setHeader("Content-Disposition", "attachment;filename=\""+fileName+"\"");

c. Create File and FileInputStream object with the downloadable resource.

File file = new File("/home/ashok/Downloads/Java.jpg");
FileInputStream fis = new FileInputStream(file);

d. Create OutputStream from response object.

OutputStream os = response.getOutputStream();

e. Get bit by bit from FileInputStream and write bit by bit to OutputStream.

int val = fis.read();
while(val != -1) {
   os.write(val);
   val = fis.read();
}

E.g

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
   <jsp:forward page="download"/>
</body>
</html>

downloadpage.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
   <head>
      <meta charset="ISO-8859-1">
      <title>Insert title here</title>
   </head>
   <body>
      <form method="post" action="download">
         <center>
            <table>
               <tr>
                  <td><img alt="JavaImage" src="/home/ashok/Java.jpg" width="200" height="200"/></td>
               </tr>
               <tr>
                  <td><input type="submit" value="Download"/></td>
               </tr>
            </table>
         </center>
      </form>
   </body>
</html>

DownloadController.java

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DownloadController {
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public String showDownloadPage() {
        return "downloadpage";
    }
    @RequestMapping(value = "/download", method = RequestMethod.POST)
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("APPLICATION/OCTET-STREAM");
        File file = new File("/home/ashok/Downloads/Java.jpg");
        FileInputStream fis = new FileInputStream(file);
        String fileName = file.getName();
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        OutputStream os = response.getOutputStream();
        int val = fis.read();
        while (val != -1) {
            os.write(val);
            val = fis.read();
        }
        fis.close();
        os.close();
    }
}

ds-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd">
   <context:annotation-config/>
   <context:component-scan base-package="com.ashok.spring.mvc.controller"/>
   <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/"/>
      <property name="suffix" value=".jsp"/>
   </bean>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
   id="WebApp_ID" version="4.0">
   <display-name>MVC</display-name>
   <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file>
      <welcome-file>default.html</welcome-file>
      <welcome-file>default.htm</welcome-file>
      <welcome-file>default.jsp</welcome-file>
   </welcome-file-list>
   <servlet>
      <servlet-name>ds</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>ds</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>
File Download in Spring MVC


Scroll to top