上传图片
springmvc中对多部件类型解析
在页面form中提交enctype="multipart/form-data"的数据时,需要springmvc对multipart类型的数据进行解析。
在springmvc.xml中配置multipart类型解析器。
<!-- 文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的最大尺寸为5MB --> <property name="maxUploadSize"> <value>5242880</value> </property> </bean>
加入commons组件jar包用于上传图片,上边的解析内部使用下边的jar进行图片上传。
创建图片虚拟 目录 存储图片
通过图形界面配置:
或者,也可以直接修改tomcat的配置:
在conf/server.xml文件,添加虚拟 目录 :
注意:在图片虚拟目录 中,一定将图片目录分级创建(提高i/o性能),一般我们采用按日期(年、月、日)进行分级创建。
上传图片代码
页面
controller方法
修改:商品修改controller方法:
@RequestMapping("/editItemsSubmit") public String editItemsSubmit(Model model, Integer id, @ModelAttribute("items") ItemsCustom itemsCustom, MultipartFile items_pic//接收商品图片 ) throws Exception { //可以直接使用model将提交pojo回显到页面 //model.addAttribute("items", itemsCustom); //原始名称 String originalFilename = items_pic.getOriginalFilename(); //上传图片 if(items_pic!=null && originalFilename!=null && originalFilename.length()>0){ //存储图片的物理路径 String pic_path = "F:\\develop\\upload\\temp\\"; //新的图片名称 String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")); //新图片 File newFile = new File(pic_path + newFileName); //将内存中的数据写入磁盘 items_pic.transferTo(newFile); //将新图片名称写到itemsCustom中 itemsCustom.setPic(newFileName); } // 调用service更新商品信息,页面需要将商品信息传到此方法 itemsService.updateItems(id, itemsCustom); model.addAttribute("result", "success"); return "items/itemsList"; }