Loading
 
What's Next: View All Tutorial →

How to upload file image or document using Spring MVC MultipartHttpServletRequest

In this article, you will learn how to upload the file using the MultipartHttpServletRequest Refer the article for For project setup   Step 1: Maven Dependency required for file upload          ...

Published Date: 23/02/2015  Last Modified Date: 23/02/2015    New Post



In this article, you will learn how to upload the file using the MultipartHttpServletRequest


Refer the article for For project setup
 

Step 1: Maven Dependency required for file upload

 

    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.0.5.RELEASE</version>
        </dependency>


        <dependency>
            <groupId>org.imgscalr</groupId>
            <artifactId>imgscalr-lib</artifactId>
            <version>4.2</version>
        </dependency>
        <!-- Apache Commons Upload -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.1</version>        
        </dependency>  


org.imgscalr - This lib is used to resize, optimize the images.

 

Step2: Dispatcher XML

 
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"

       xmlns:util="http://www.springframework.org/schema/util"       
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
		
    <mvc:annotation-driven  />
    <context:component-scan base-package="com.tutorial.web" />    
  
    <mvc:resources mapping="/img/**" location="file:D:/resource/img/" />    
    <!-- Allows for mapping the DispatcherServlet to "/" by forwarding static resource requests to the container's default Servlet -->
    <mvc:default-servlet-handler/>
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <!--<property  name="maxUploadSize" value="512000" />-->
        <!--        <property name="uploadTempDir" ref="uploadDirResource" />-->
    </bean>
    
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
  
</beans>


multipartResolver - used to handle file upload
mvc:resources mapping="/img/**" location="file:D:/resource/img/" - This map the location. It help to access all the file with the /img/<filename>

For example if  1.jpg is stored in the system file pat D:/resource/img, we can access it using http://localhost:8080/contextpath/img/1.jpg

 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Application Form</h1>
        <form name="appFrm" action="<%=request.getContextPath()%>/saveAndViewApplicationData" enctype="multipart/form-data" method="post">
            <table>
               <tr>
                    <td>Photo : </td>
                    <td><input type="file" name="fileImg"  /> 
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="Submit"/></td>
                </tr>
            </table>

        </form>
    </body>
</html>


enctype="multipart/form-data"  - Need to upload file


Controller function to receive the file and save it into FTP path
 
 @RequestMapping("/saveAndViewApplicationData")
    public String saveApplicationForm(ModelMap map, @RequestParam String userName, HttpServletRequest request) {

        //Using @RequestParam
        System.out.println("UserName using @RequestParam :: " + userName);

        //Using request.getParameter()
        System.out.println("UserName using request.getParamter :: " + request.getParameter("userName"));
        System.out.println(request.getParameter("gender"));
        System.out.println(request.getParameter("ageGroup"));

        //Setting data in the ModelMap object to display data in the jsp
        map.addAttribute("uName", request.getParameter("userName"));
        map.addAttribute("gndr", request.getParameter("gender"));
        map.addAttribute("age", request.getParameter("ageGroup"));
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("fileImg");

        String path = "D:/resource/img/" + multipartFile.getOriginalFilename().toLowerCase();

        map.addAttribute("path", "/img/" + multipartFile.getOriginalFilename().toLowerCase());

        System.out.println(path);
        File file = new File(path);

        BufferedImage image = null;
        try {
            image = ImageIO.read(new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException ex) {
            System.out.println(ex);
        }

        try {

            if (multipartFile.getSize() >= 325000) {
                boolean status = ImageIO.write(resize(image, Method.ULTRA_QUALITY, 1000, Scalr.THRESHOLD_QUALITY_BALANCED), "JPG", file);
                image = ImageIO.read(file);
                if (status == false) {
                    return "img.005";
                }
            } else if (multipartFile.getSize() >= 125000) {
                boolean status = ImageIO.write(resize(image, Method.ULTRA_QUALITY, 600, Scalr.THRESHOLD_QUALITY_BALANCED), "JPG", file);
                image = ImageIO.read(file);

                if (status == false) {
                    return "img.005";
                }
            } else {
                multipartFile.transferTo(file);

            }

        } catch (IOException ex) {
            System.out.println(ex);
        }
        return "applicationFormData";
    }
 

Output:


Hit the url :
http://localhost:8084/SpringMVC/showApplicationForm

upload the file and view the data.

Make sure you create the folder in the path D:/resource/img

Download the project


https://drive.google.com/file/d/0B_9jt9kIlxciellsd0dtR0lrbEk/view?usp=sharing

 
Awaiting for Administrator approval





Tags: Forms Handling Spring MVC

← Back to list


Related Post




×