Nearby lessons

28 of 35

Spring - File Upload and Download

📌 What You Will Learn
  • Build a form that can carry a file, and say why enctype matters
  • Configure a MultipartResolver in the Spring configuration file
  • Write controllers for both the upload and the download direction

Uploading and downloading files in Spring Web MVC — the multipart form, the MultipartResolver configuration, the commons-fileupload and commons-io jars, the upload controller, and a controller that streams a file back to the browser.

File Upload in Spring WEB MVC

IN general, in web applications, it is very frequent to perform upload operations inorder to upload files from client to Server.

To perform File Upload operation in SPring WEB MVC applications, Spring WEB MVC framework has provided some predefined library in the form of "org.springframework.web.multipart.commons.CommonsMultipartResolver"

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

Prepare a user form with File components — uploadform.jsp

  • In User form , we must specify "POST" as "method" attribute in form tag.
  • in User form, we must provide "multipart/form-data" as "enctype" attribute in form tag.

EX:

Example02
JCode Cell
1 
2<form method="POST" action="upload" enctype="multipart/form-data">
3<center>
4<table>
5<tr>
6 
7 <td>File1</td><td><input type="file" name="file"/></td>
8</tr>
9</table>
10</center>
11</form>
12

EX:UploadController.java

@Controller public class UploadController {

----- @RequestMapping(value="/upload", method=RequestMethod.POST) public ModelAndView uploadFiles(@RequestParam MultipartFile file) { String status = ""; try{ String file_Name = multipartFile.getOriginalFilename(); FileOutputStream fos = new FileOutputStream("E:/uploads/"+file_Name); byte[] bt = multipartFile.getBytes(); fos.write(bt); status = "SUCCESS";

} catch (Exception e) { status = "FAILURE"; e.printStackTrace();

} return new ModelAndView("status", "status", status); } }

  • Configure CommonsMultipartResolver class as bean with the name "multipartResolver" in

spring configuration file

EX: ds-servlet.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

Note: For File Upload operation, Spring Framework is using Commons File Upload library internally, so that, we must provide the following JAR files in web application lib folder along with all Spring JARs.

commons-fileupload-1.4.jar commons-io-2.6.jar — index.jsp

Example:

Example05
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="upload"/>
12</body>
13</html>
14

commons-fileupload-1.4.jar commons-io-2.6.jar — uploadform.jsp

Example06
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h2 style="color: red;" align="center">File Upload Form</h2>
12<form method="POST" action="upload" enctype="multipart/form-data">
13<center>
14<table>
15<tr>
16<td>File1</td><td><input type="file" name="file"/></td>
17</tr>
18<tr>
19<td>File2</td><td><input type="file" name="file"/></td>
20</tr>
21<tr>
22<td>File3</td><td><input type="file" name="file"/></td>
23</tr>
24<tr>
25<td><input type="submit" value="Upload"/></td>
26</tr>
27</table>
28</center>
29</form>
30</body>
31</html>
32

commons-fileupload-1.4.jar commons-io-2.6.jar — status.jsp

Example07
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<h1 style="color: red;" align="center">Files Upload Status: ${status}</h1>
12</body>
13</html>
14

commons-fileupload-1.4.jar commons-io-2.6.jar — UploadController.java

Example08
JCode Cell
1 
2package com.durgasoft.controller;
3 
4import java.io.FileOutputStream;
5 
6import org.springframework.stereotype.Controller;
7import org.springframework.web.bind.annotation.RequestMapping;
8import org.springframework.web.bind.annotation.RequestMethod;
9import org.springframework.web.bind.annotation.RequestParam;
10import org.springframework.web.multipart.MultipartFile;
11import org.springframework.web.servlet.ModelAndView;
12 
13@Controller
14public class UploadController {
15@RequestMapping(value="/upload", method=RequestMethod.GET)
16public String showUploadForm() {
17return "uploadform";
18}
19 
20@RequestMapping(value="/upload", method=RequestMethod.POST)
21public ModelAndView uploadFiles(@RequestParam MultipartFile[] file) {
22String status = "";
23 
24try {
25 for(MultipartFile multipartFile: file) {
26 String file_Name = multipartFile.getOriginalFilename();
27 FileOutputStream fos = new FileOutputStream("E:/uploads/"+file_Name);
28 byte[] bt = multipartFile.getBytes();
29 fos.write(bt);
30 status = "SUCCESS";
31 }
32 
33} catch (Exception e) {
34 status = "FAILURE";
35 e.printStackTrace();
36}
37return new ModelAndView("status", "status", status);
38}
39}
40

commons-fileupload-1.4.jar commons-io-2.6.jar — ds-servlet.xml

Example09
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12 
13<context:component-scan base-package = "com.durgasoft.controller" />
14 
15<bean id="multipartResolver"
16 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
17 
18<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
19<property name = "prefix" value = "/WEB-INF//" />
20<property name = "suffix" value = ".jsp" />
21</bean>
22 
23</beans>
24

commons-fileupload-1.4.jar commons-io-2.6.jar — web.xml

Example10
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<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">
4<display-name>exception_handling_web</display-name>
5<welcome-file-list>
6<welcome-file>index.html</welcome-file>
7<welcome-file>index.htm</welcome-file>
8<welcome-file>index.jsp</welcome-file>
9<welcome-file>default.html</welcome-file>
10<welcome-file>default.htm</welcome-file>
11<welcome-file>default.jsp</welcome-file>
12</welcome-file-list>
13<servlet>
14<servlet-name>ds</servlet-name>
15<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16<load-on-startup>1</load-on-startup>
17</servlet>
18 
19<servlet-mapping>
20<servlet-name>ds</servlet-name>
21<url-pattern>/</url-pattern>
22</servlet-mapping>
23</web-app>
24

File Downloading in Spring WEB MVC — downloadpage.jsp

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.

  • Prepare a File with "Download" button and with the downloadable resource.

EX:

Example11
JCode Cell
1 
2<form method=‖post‖ action=‖download‖>
3<img alt=‖Java_Python_Image‖ src=‖E:\images\Java_Python.jpg‖ width=‖200‖ height=‖200‖/>
4<br>
5<input type=‖submit‖ value=‖Download‖/></td>
6</form>
7

Prepare Controller class — index.jsp

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

  • Set Content Type as "APPLICATION/OCTET-STREAM".

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

  • Set "content-disposition" response header to response object.

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

  • Create File and FileInputStream object with the downloadable resource.

File file = new File("E:\\images\\Java_Python.jpg"); FileInputStream fis = new FileInputStream(file);

  • Create OutputStream from response object.

OutputStream os = response.getOutputStream()

  • 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();

Example:

Example12
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="download"/>
12</body>
13</html>
14

Prepare Controller class — downloadpage.jsp

Example13
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<!DOCTYPE html>
5<html>
6<head>
7<meta charset="ISO-8859-1">
8<title>Insert title here</title>
9</head>
10<body>
11<form method="post" action="download">
12<center>
13<table>
14<tr>
15<td><img alt="Java_Python_Image" src="E:\images\Java_Python.jpg" width="200" height="200"/></td>
16</tr>
17<tr>
18<td><input type="submit" value="Download"/></td>
19</tr>
20</table>
21</center>
22</form>
23</body>
24</html>
25

Prepare Controller class — DownloadController.java

Example14
JCode Cell
1 
2package com.durgasoft.controller;
3 
4import java.io.File;
5import java.io.FileInputStream;
6import java.io.OutputStream;
7 
8import javax.servlet.http.HttpServletRequest;
9import javax.servlet.http.HttpServletResponse;
10 
11import org.springframework.stereotype.Controller;
12import org.springframework.web.bind.annotation.RequestMapping;
13import org.springframework.web.bind.annotation.RequestMethod;
14import org.springframework.web.servlet.ModelAndView;
15 
16@Controller
17public class DownloadController {
18@RequestMapping(value="/download",method=RequestMethod.GET)
19public String showDownloadPage() {
20return "downloadpage";
21}
22@RequestMapping(value="/download", method=RequestMethod.POST)
23public void download(HttpServletRequest request, HttpServletResponse response)throws Exception {
24response.setContentType("APPLICATION/OCTET-STREAM");
25File file = new File("E:\\images\\Java_Python.jpg");
26FileInputStream fis = new FileInputStream(file);
27String fileName = file.getName();
28response.setHeader("Content-Disposition", "attachment;filename=\""+fileName+"\"");
29 
30OutputStream os = response.getOutputStream();
31int val = fis.read();
32 
33while(val != -1) {
34 os.write(val);
35 val = fis.read();
36}
37fis.close();
38os.close();
39}
40}
41

Prepare Controller class — ds-servlet.xml

Example15
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/context
11http://www.springframework.org/schema/context/spring-context.xsd">
12 
13<context:component-scan base-package = "com.durgasoft.controller" />
14<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
15<property name = "prefix" value = "/WEB-INF//" />
16<property name = "suffix" value = ".jsp" />
17</bean>
18 
19</beans>
20

Prepare Controller class — web.xml

Example16
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<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">
4<display-name>exception_handling_web</display-name>
5<welcome-file-list>
6<welcome-file>index.html</welcome-file>
7<welcome-file>index.htm</welcome-file>
8<welcome-file>index.jsp</welcome-file>
9<welcome-file>default.html</welcome-file>
10<welcome-file>default.htm</welcome-file>
11<welcome-file>default.jsp</welcome-file>
12</welcome-file-list>
13<servlet>
14<servlet-name>ds</servlet-name>
15<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16<load-on-startup>1</load-on-startup>
17</servlet>
18<servlet-mapping>
19<servlet-name>ds</servlet-name>
20<url-pattern>/</url-pattern>
21</servlet-mapping>
22</web-app>
23
📝 Key Takeaways
  • Without a MultipartResolver bean the upload silently arrives as an ordinary parameter
  • commons-fileupload and commons-io are required alongside the Spring jars
  • Downloading is a matter of setting the response headers and writing the bytes yourself