<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的最大尺寸为5MB --> <property name="maxUploadSize"> <value>5242880</value> </property> </bean>
CommonsMultipartResolver 解析器依赖 commons-fileupload 和 commons-io ,加入如下 jar 包:
1、controller :
//商品修改提交 @RequestMapping("/editItemSubmit") public String editItemSubmit(Items items, MultipartFile pictureFile)throws Exception{ //原始文件名称 String pictureFile_name = pictureFile.getOriginalFilename(); //新文件名称 String newFileName = UUID.randomUUID().toString()+pictureFile_name.substring(pictureFile_name.lastIndexOf(".")); //上传图片 File uploadPic = new java.io.File("F:/develop/upload/temp/"+newFileName); if(!uploadPic.exists()){ uploadPic.mkdirs(); } //向磁盘写文件 pictureFile.transferTo(uploadPic); .....
2、 页面:
form 添加 enctype="multipart/form-data" :
<form id="itemForm" action="${pageContext.request.contextPath }/item/editItemSubmit.action" method="post" enctype="multipart/form-data"> <input type="hidden" name="pic" value="${item.pic }" />
file 的 name 与 controller 形参一致:
<tr> <td>商品图片</td> <td><c:if test="${item.pic !=null}"> <img src="/pic/${item.pic}" width=100 height=100 /> <br /> </c:if> <input type="file" name="pictureFile" /></td> </tr>