ssm學習筆記——上傳圖片
阿新 • • 發佈:2018-11-02
一:環境
1.導包
commons-fileupload-1.2.2.jar
commons-io-2.4.jar
二:上傳圖片
1.一些說明
1)虛擬訪問路徑
是為了把圖片放到Apach伺服器專案以外的磁碟目錄
2)input的name要求
name的值需要和Controller的MultipartFile的名稱一致。當然也可以註解改名字。
3)input的屬性
enctype="multipart/form-data"
4)springmvc.xml配置實體類
·id是固定的
·可以在其中配置上傳的一些條件
2.實現
1)設定虛擬訪問路徑
2)Controller層實現程式碼
@RequestMapping(value = "/updateitem.action") public ModelAndView update(Items items, MultipartFile pictureFile) throws IllegalStateException, IOException { ModelAndView mav = new ModelAndView(); String name= UUID.randomUUID().toString().replaceAll("-", ""); String ext = FilenameUtils.getExtension(pictureFile.getName()); items.setPic(name + "." + ext); pictureFile.transferTo(new File("D:\\Study\\upload\\" + name + "." + ext)); service.update(items); mav.setViewName("success"); return mav; }
3)前端新增input提交檔案
<form id="itemForm" action="${pageContext.request.contextPath }/updateitem.action" method="post" enctype="multipart/form-data"> <input type="hidden" name="id" value="${item.id }" /> 修改商品資訊: <table width="100%" border=1> <tr> <td>商品名稱</td> <td><input type="text" name="name" value="${item.name }" /></td> </tr> <tr> <td>商品價格</td> <td><input type="text" name="price" value="${item.price }" /></td> </tr> <tr> <td>商品生產日期</td> <td><input type="text" name="createtime" value="${item.createtime}" /></td> </tr> <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> <tr> <td>商品簡介</td> <td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea> </td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="提交" /> </td> </tr> </table> </form>View Code
4)springmvc.xml中配置實現類
<!-- 配置檔案上傳類 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上傳圖片的大小 B 5M 1*1024*1024*5--> <property name="maxUploadSize" value="5000000"/> </bean>