1. 程式人生 > >SpringMVC之文件圖片上傳

SpringMVC之文件圖片上傳

一.Jsp頁面

<form name="Form" action="/SpringMVC/upateItem" method="post"  enctype="multipart/form-data">
<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="itemsPic"/>   
</td>  
</tr>
</form> 

二、spring-mvc.xml配置檔案上傳解析器

<!-- 檔案上傳,id必須設定為multipartResolver -->
<!-- 定義檔案上傳解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 設定預設編碼 -->
    <property name="defaultEncoding" value="UTF-8"></property>
    <!-- 設定檔案上傳的最大值為5MB,5*1024*1024 -->
    <property name="maxUploadSize" value="5242880"></property>
    <!-- 設定檔案上傳時寫入記憶體的最大值,如果小於這個引數不會生成臨時檔案,預設為10240 -->
    <property name="maxInMemorySize" value="40960"></property>
    <!-- 上傳檔案的臨時路徑 -->
    <property name="uploadTempDir" value="fileUpload/temp"></property>
    <!-- 延遲檔案解析 -->
    <property name="resolveLazily" value="true"/>
</bean>

三、Controller控制器接收itemsPic引數

@RequestMapping("updateItem")
public String updateItemById(Item item, MultipartFile itemsPic) throws Exception {
	// 圖片上傳
	// 設定圖片名稱,不能重複,可以使用uuid
	String picName = UUID.randomUUID().toString();

	// 獲取檔名
	String oriName = itemsPic.getOriginalFilename();
	// 獲取圖片字尾
	String extName = oriName.substring(oriName.lastIndexOf("."));

	// 開始上傳
	itemsPic.transferTo(new File("C:/upload/image/" + picName + extName));

	// 設定圖片名到商品中
	item.setPic(picName + extName);
	// ---------------------------------------------
	// 更新商品
	this.itemService.updateItemById(item);

	return "forward:/itemEdit.action";
}