springMVC圖片檔案上傳功能的實現
- 在工程依賴庫下新增檔案上傳jar包
commons-fileupload-1.2.2.jar
commons-io-2.4.jar
2.jsp頁面設定form表單屬性enctype
在表單中上傳圖片時,需要在form的屬性設定中新增enctype="multipart/form-data"。
[html] view plain copy
<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進位制的方式傳過去。
- springMVC.xml新增multipart型別解析器
在頁面form中提交enctype="multipart/form-data"的資料時,需要springmvc對multipart型別的資料進行解析,需要在springmvc.xml中配置multipart型別解析器。
[html] view plain copy
<!-- 檔案上傳 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 設定上傳檔案的最大尺寸為5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property >
</bean>
4.建立圖片虛擬目錄,以存放圖片
eclipse IDE 通過介面進行配置:servers -->Tomcat v8.0 Server at localhost--> 雙擊,選擇-->add external web modules.
在圖片虛擬目錄中,一定將圖片目錄分級建立(提高i/o效能),一般我們採用按日期(年、月、日)進行分級建立。
- jsp 頁面,設定圖片顯示的位置和大小。
[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>
- Controller 類方法中寫相應的方法
<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.測試效果