今天在上传图片时,总是报400错误:
日志信息:
Field error in object 'user' on field 'age': rejected value [ss]; codes [typeMismatch.user.age,typeMismatch.age,typeMismatch.java.lang.Integer,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.age,age]; arguments []; default message [age]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'age'; nested exception is java.lang.NumberFormatException: For input string: "ss"]
Field error in object 'user' on field 'image': rejected value [org.springframework.web.multipart.commons.CommonsMultipartFile@503f5e3c]; codes [typeMismatch.user.image,typeMismatch.image,typeMismatch.java.lang.String,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.image,image]; arguments []; default message [image]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.commons.CommonsMultipartFile' to required type 'java.lang.String' for property 'image'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type [java.lang.String] for property 'image': no matching editors or conversion strategy found]
后来找出原因:表单里上传图片的 name值要与对应的controller的方法参数一致。且不能与bean的属性同名
bean:
jsp:
controller:
上传图片注意事项:
1.<form class="layui-form" action="${pageContext.request.contextPath }/doAddUser" method="post" enctype="multipart/form-data"></form>
2.表单里上传图片的 name值要与对应的controller的方法参数一致。且不能与bean的属性同名
3.public String doAddUser(User user,MultipartFile photo) throws IllegalStateException, IOException{}
4.需要在springMVC.xml配置:
<!-- 配置上传图片实现类 注意:此处id名固定为:commonsMultipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 可以控制上传图片的大小 单位:B --> <property name="maxUploadSize" value="104857600"></property> </bean>
=============================================================================================================
=====================================================================================
记录一下:给Tomcat服务器另配一个路径来访问图片(此处配的是E盘下的photo文件夹)
然后访问 E盘下的photo文件夹 里 图片的方式: