[英]Spring Web MVC Cannot upload file to server
I am trying to upload an image via Spring MVC. 我正在尝试通过Spring MVC上传图像。
Controller.java 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 欢迎-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 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. 到servlet.xml文件。 I am using Spring 4.
我正在使用Spring 4。
You need to have separate parameter in editProfileHandlerController
method like @RequestParam("file") MultipartFile file
. 您需要在
editProfileHandlerController
方法中使用单独的参数,例如@RequestParam("file") MultipartFile file
。
Issue is Spring internally adds parameter resolver based on parameter type. 问题是Spring在内部基于参数类型添加了参数解析器。 In your case your wrapping
MultipartFile
field in your custom type Users
that's why it is not working. 在您的情况下,在您的自定义类型“
Users
中包装了MultipartFile
字段,这就是它不起作用的原因。
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)
更改您的多部分类名。例如org.springframework.web.multipart.commons.CommonsMultipartResolver.CommonsMultipartResolver
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.