springmvc上傳圖片例項
阿新 • • 發佈:2019-02-07
springmvc上傳圖片
1、需求
在修改商品頁面,新增上傳商品圖片功能
2、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>
3、加入上傳圖片的jar
通過修改tomcat的配置:
在Tomcat安裝目錄下找到conf/server.xml檔案,新增虛擬目錄:
<Context docBase="F:\tomcat\uploadFile" path="/pic" reloadable="false"/>
注意:在圖片虛擬目錄中,一定將圖片目錄分級建立(提供i/o效能),一般採取日期(年月日)進行分級建立。
5、上傳圖片程式碼
頁面:
<table> <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="item_pic"/> </td> </tr> </table>
controller類中方法:
//在需要校驗的pojo前面新增@Validated,在需要校驗的pojo後邊新增BindingResult bindingResult接收校驗出錯資訊 //注意:@validated和BindingResult bindingResult是配對出現,並且形參順序是固定的(一前一後) //... //獲取校驗錯誤資訊 if(bindingResult.hasErrors()){ //輸出錯誤資訊 List<ObjectError> allErrors = bindingResult.getAllErrors(); for(ObjectError objectError:allErrors){ //輸出錯誤資訊 System.out.println(objectError.getDefaultMessage()); } //將錯誤資訊傳到頁面 model.addAttribute("allErrors", allErrors); return "items/editItems"; } //原始名稱 String originalFileName = items_pic.getOriginalFilename(); //上傳圖片 if(items_pic!=null && originalFileName!=null && originalFileName.length()>0){ //物理路徑 String pic_path = "F:\\pic\\2016"; //新的圖片名稱 String newFileName = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf(".")); //新圖片 File newFile = new File(pic_path + newFileName); //將記憶體中的資料寫入磁碟中 items_pic.transferTo(newFile); //將新的圖片名稱寫到itemsCustom中 itemsCustom.setPic(newFileName); } return "success"; }