Spring Web MVC无法将文件上传到服务器

时间:2016-02-29 07:16:27

标签: java spring jsp spring-mvc

我正在尝试通过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:/");
    }

欢迎-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>

错误:

HTTP Status 400 -

type Status report

message

description The request sent by the client was syntactically incorrect.

上传图片时为何会出现此错误?

添加

时出现此错误
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576" />
 </bean>

到servlet.xml文件。我正在使用Spring 4.

2 个答案:

答案 0 :(得分:1)

您需要在editProfileHandlerController方法中设置单独的参数,例如@RequestParam("file") MultipartFile file

问题是Spring内部添加了基于参数类型的参数解析器。 在您的情况下,您的自定义类型MultipartFile中的Users包裹字段就是它无效的原因。

修改您的方法,如下所示:

@RequestMapping(value = "/editprofilehandler", method=RequestMethod.POST)
public ModelAndView editProfileHandlerController(@ModelAttribute("userForm") Users users
        ,@RequestParam("uploadImage") MultipartFile file, ModelMap model, HttpSession session)

答案 1 :(得分:1)

更改你的多部分类名称 的 org.springframework.web.multipart.commons.CommonsMultipartResolver.CommonsMultipartResolver