上傳圖片
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"; }