2016-02-29 103 views
1

我想通過Spring MVC上傳圖片。春季Web 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文件中我得到這個錯誤。我正在使用彈簧4.

+0

HTTP:// WWW .ioncannon.net/programming/975/spring-3-file-upload-example/ – StanislavL

回答

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

改變你的多類name.like org.springframework.web.multipart.commons.CommonsMultipartResolver.CommonsMultipartResolver