1

I am trying to upload an image via Spring MVC.

Controller.java

@SuppressWarnings("resource")
    @RequestMapping(value = "/editprofilehandler", method=RequestMethod.POST)
    public ModelAndView editProfileHandlerController(@ModelAttribute("userForm") Users users
            , ModelMap model, HttpSession session)
    {       
        if(session.getAttribute("session_user") != null){
            try
            {
                InputStream inputStream = null;
                OutputStream outputStream = null;
                MultipartFile file = users.getImage();
                String fileName = file.getOriginalFilename();
                inputStream = file.getInputStream();

                File newFile = new File("C:/Documents and Settings/smart/workspace/Pir/WebContent/resources/images/profile/" + fileName);
                if(!newFile.exists())
                {
                    model.addAttribute("exc", "File Does not exist");
                }
                model.addAttribute("exc", newFile.getName());
                outputStream = new FileOutputStream(newFile);
                int read = 0;
                byte[] bytes = new byte[1024];

                while((read = inputStream.read(bytes)) != -1)
                    outputStream.write(bytes, 0, read);

            }
            catch(Exception e){
                //model.addAttribute("exc", e.getMessage() + "df");
            }
            List<Object[]> userDetails = this.userFunctionsService.getUserDetails(((UserLoginDetails)session.getAttribute("session_user")).getEmailID());
            model.addAttribute("userDetails", userDetails);
            return new ModelAndView("editProfile", model);
        }
        else
            return new ModelAndView("redirect:/");
    }

welcome-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"
    xmlns:mvc="http://www.springframework.org/schema/mvc">

    <context:annotation-config />

    <context:component-scan base-package="com.pir" />
    <mvc:annotation-driven />
    <tx:annotation-driven transaction-manager="myTransactionManager" />

    <bean id="myTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576" />
    </bean>

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="com.mysql.jdbc.Driver"
    p:url="jdbc:mysql://localhost:3306/pir"
    p:username="root"
    p:password="user" />

    <bean id="tilesViewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass">
            <value>
                org.springframework.web.servlet.view.tiles3.TilesView
            </value>
        </property> 
    </bean>
    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles.xml</value>
            </list>
        </property>
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />
</beans>

editProfile.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

${exc }
<table>
<c:forEach items="${userDetails}" var="element">
    <tr>
        <td valign="top">
            <a href="${pageContext.request.contextPath }/changeimage">
                <img src="${pageContext.request.contextPath }/resources/images/profile/${element[5] }" height="145" width="200" />
            </a>
        </td>
        <td>
            <form:form action="${pageContext.request.contextPath}/editprofilehandler" method="POST" modelAttribute="userForm" enctype="multipart/form-data">
            <table>
                <tr>
                    <td>
                        First Name :
                    </td>
                    <td>
                        <form:input path="firstName" value="${element[2] }" /> <form:errors path="firstName" class="error" />
                    </td>
                </tr>
                <tr>
                    <td>
                        Last Name :
                    </td>
                    <td>
                        <form:input path="lastName" value="${element[3] }" /> <form:errors path="lastName" class="error" />
                    </td>
                </tr>
                <tr>    
                    <td>
                        EmailID Name :
                    </td>
                    <td>
                        <form:input path="emailID" value="${element[1] }" /> <form:errors path="emailID" class="error" />
                    </td>
                </tr>
                <tr>
                    <td>
                         Mobile No :
                    </td>
                    <td>
                        <form:input path="mobileNo" value="${element[4] }" /> <form:errors path="mobileNo" class="error" />
                    </td>
                </tr>
                <tr>    
                    <td>
                        Date of birth :
                    </td>
                    <td>
                        <form:input path="dateOfBirth" value="${element[6]}" /> <form:errors path="dateOfBirth" class="error" />
                    </td>
                </tr>
                <tr>
                    <td>
                        Gender :
                    </td>
                    <td>
                        <form:input path="gender" value="${element[7]}" /> <form:errors path="gender" class="error" />
                    </td>
                </tr>
                <tr>
                    <td>
                        Profile image :
                    </td>
                    <td>
                        <input type="file" name="uploadImage" />
                    </td>
                </tr>
                <tr>
                    <td align="center" colspan="2">
                        <input type="submit" value="Update" />
                    </td>
                </tr>
            </table>
            </form:form>
        </td>
    </tr>
</c:forEach>
</table>

Error:

HTTP Status 400 -

type Status report

message

description The request sent by the client was syntactically incorrect.

Why this error is coming while uploading the image?

I am getting this error when I add

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576" />
 </bean>

to the servlet.xml file. I am using Spring 4.

1

2 Answers 2

1

You need to have separate parameter in editProfileHandlerController method like @RequestParam("file") MultipartFile file.

Issue is Spring internally adds parameter resolver based on parameter type. In your case your wrapping MultipartFile field in your custom type Users that's why it is not working.

Modify your method like below will work:

@RequestMapping(value = "/editprofilehandler", method=RequestMethod.POST)
public ModelAndView editProfileHandlerController(@ModelAttribute("userForm") Users users
        ,@RequestParam("uploadImage") MultipartFile file, ModelMap model, HttpSession session)
Sign up to request clarification or add additional context in comments.

Comments

1

change your multipart class name.like org.springframework.web.multipart.commons.CommonsMultipartResolver.CommonsMultipartResolver

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.