commons-fileupload-1.2.2.jarhtml
commons-io-2.4.jarjava
2.jsp页面设置form表单属性enctypeweb
在表单中上传图片时,须要在form的属性设置中添加enctype="multipart/form-data"。spring
[html] view plain copymvc
<form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" method="post" enctype="multipart/form-data" >
表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认状况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操做. enctype="multipart/form-data"是上传二进制数据;form里面的input的值以2进制的方式传过去。app
在页面form中提交enctype="multipart/form-data"的数据时,须要springmvc对multipart类型的数据进行解析,须要在springmvc.xml中配置multipart类型解析器。dom
[html] view plain copyeclipse
<!-- 文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的最大尺寸为5MB --> <property name="maxUploadSize"> <value>5242880</value> </property> </bean>
4.建立图片虚拟目录,以存放图片jsp
eclipse IDE 经过界面进行配置:servers -->Tomcat v8.0 Server at localhost--> 双击,选择-->add external web modules.post
在图片虚拟目录中,必定将图片目录分级建立(提升i/o性能),通常咱们采用按日期(年、月、日)进行分级建立。
[html] view plain copy
<tr> <td>商品图片</td> <td> <c:if test="${itemsCustom.pic !=null}"> <img src="/pic/${itemsCustom.pic}" width=100 height=100/> <br/> </c:if> <input type="file" name="items_pic"/> </td> lt;/tr>
<1, 方法的参数中添加MultipartFile items_pic行参 这个跟页面的图片的参数名字是一致的;
<2, 为了不文件名称相同而冲突,使用UUID.randomUUID()产生一个随机的数值做为名称;
<3. 将图片数据写入磁盘:items_pic.transferTo(newFile);
<4. 更新itemsCustom中属性pic的值itemsCustom.setPic(newFileName);
[java] view plain copy
//在须要校验的poJo类前加 @Validated, 后面加BindingResult bindingResult 存放出错信息。 @RequestMapping("/editItemsSubmit") public String editItemsSubmit(Model model, HttpServletRequest request,Integer id, @Validated ItemsCustom itemsCustom, BindingResult bindingResult, MultipartFile items_pic)throws Exception { if(bindingResult.hasErrors()){ List<ObjectError> allErrors = bindingResult.getAllErrors(); for(ObjectError objectError :allErrors){ System.out.println(objectError.getDefaultMessage()); } model.addAttribute("allErrors", allErrors); model.addAttribute("itemsCustom", itemsCustom); return "items/editItems"; } //原始名称 String originalFilename = items_pic.getOriginalFilename(); //上传图片 if(items_pic!=null && originalFilename!=null && originalFilename.length()>0){ //存储图片的物理路径 String pic_path = "C:\\Users\\Administrator.MICROSO-U8JSS8B\\Desktop\\java_code\\picture\\"; //新的图片名称 String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")); //新图片 File newFile = new File(pic_path+newFileName); //将内存中的数据写入磁盘 items_pic.transferTo(newFile); //将新图片名称写到itemsCustom中 itemsCustom.setPic(newFileName); } itemsService.updateItems(id, itemsCustom); // return "success"; return "forward:queryItems.action"; }
7.测试效果
参考:http://zkliqiang.iteye.com/blog/779285