SSM框架修改資料中實現圖片上傳功能
阿新 • • 發佈:2019-01-23
第一步:當然是需要加入必要的兩個jar包
commons-fileupload-1.3.jar、commons-io-1.2.jar
或者引入依賴:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId >org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
第二步:首先要在我們的springMVC.xml檔案中新增上傳檔案解析器
<!-- 配置多媒體檔案解析器 -->
<!-- 檔案上傳 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- 設定預設編碼 -->
<property name="defaultEncoding" value="utf-8"></property>
<!-- 設定上傳檔案的最大尺寸為5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
第三步:然後我們要在WebRoot目錄下建立一個“upload”資料夾
這個名字你們可以隨便取,呼叫的時候就呼叫你取的這個名字就行了
上傳的檔案會出現在伺服器上的tomcat下面的專案名裡的upload下面
例如我的是這個:E:\apache-tomcat-7.0.90\webapps\專案名\upload
第四步:修改頁面jsp中的部分程式碼:
效果如圖:
首先是JavaScript:
<script type="text/javascript">
//下面用於圖片上傳預覽功能
function setImagePreview(avalue) {
var docObj=document.getElementById("doc");
var imgObjPreview=document.getElementById("preview");
if(docObj.files &&docObj.files[0])
{
//火狐下,直接設img屬性
imgObjPreview.style.display = 'block';
imgObjPreview.style.width = '100px';
imgObjPreview.style.height = '100px';
//imgObjPreview.src = docObj.files[0].getAsDataURL();
//火狐7以上版本不能用上面的getAsDataURL()方式獲取,需要一下方式
imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
}
else
{
//IE下,使用濾鏡
docObj.select();
var imgSrc = document.selection.createRange().text;
var localImagId = document.getElementById("localImag");
//必須設定初始大小
localImagId.style.width = "150px";
localImagId.style.height = "180px";
//圖片異常的捕捉,防止使用者修改後綴來偽造圖片
try{
localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
}
catch(e){
alert("您上傳的圖片格式不正確,請重新選擇!");
return false;
}
imgObjPreview.style.display = 'none';
document.selection.empty();
}
return true;
}
</script>
下面是form裡面的內容:
<form action="goods/updateGoods.do" method="post" enctype="multipart/form-data" >
<ul class="forminfo">
<input type="hidden" name="macId" value="${goods.macId }" />
<li><label>名稱:</label><input id="goodsName" name="goodsName"
value="${goods.goodsName }" class="dfinput" /><br></li>
<li><label>描述:</label><input id="goodsDesc" name="goodsDesc"
value="${goods.goodsDesc }" class="dfinput" /><br></li>
<li><label>圖片:</label>
<div id="localImag">
<img id="preview" src="http://localhost:8080/third_vm/${goods.goodsPic}" width="100" height="100">
</div>
<input type="file" id="doc" name="file" onchange="javascript:setImagePreview();" /><br></li>
<li><label>價格:</label><input id="goodsPrice" name="goodsPrice"
value="${goods.goodsPrice }" class="dfinput" /><br></li>
<li><label>成本:</label><input id="goodsNetPrice" name="goodsNetPrice"
value="${goods.goodsNetPrice }" class="dfinput" /><br></li>
<li><label>重量:</label><input id="goodsWeight" name="goodsWeight"
value="${goods.goodsWeight }" class="dfinput" /><br></li>
<li><label>單位:</label><input id="goodsUnit" name="goodsUnit"
value="${goods.goodsUnit }" class="dfinput" /><br></li>
<li><label>有效期:</label><input id="goodsExpiration" name="goodsExpiration"
value="${goods.goodsExpiration }" class="dfinput" /><br></li>
<li><label>屬性:</label><input id="goodsAttribute" name="goodsAttribute"
value="${goods.goodsAttribute }" class="dfinput" /><br></li>
<li><input type="submit" value="修改" class="scbtn" /> <input
type="button" name="Submit" onclick="javascript:history.back(-1);"
value="返回" class="scbtn" />
</li>
</ul>
</form>
敲黑板!!劃重點了!!
這裡有幾個地方需要注意:
第一:提交的方式需要是POST
第二:需要新增enctype="multipart/form-data"
第三:也是最重要的一點
這裡使用的是pojo類下的goodsPic 來儲存圖片的路徑和名稱(顯示的時候需要用到)
在jsp頁面中,input的name屬性一定不能與pojo類的存貯屬性名相同,不然就會報錯HTTP 400
就因為這個折騰了半天才查出來原因,debug也用了 竟然發現頁面跳轉直接就不會進入controller方法裡面 直接就報錯了,很是莫名其妙!
為了和屬性區分,這裡使用的是file ,因為在修改資料的時候,還有實體類物件傳入controller,所以不能重名。
第四步:上傳圖片的Controller類的程式碼(這裡面的“upload”就是我們建立的資料夾的名稱):
@RequestMapping("/updateGoods")
public String updateGoods(@RequestParam(value="file")MultipartFile pictureFile,HttpServletRequest request, Goods goods, String goodsName, String macId) throws IOException{
//這個RequestParam(value="file")的是我們在jsp的name=“file”
// 使用UUID給圖片重新命名,並去掉四個“-”
String name = UUID.randomUUID().toString().replaceAll("-", "");
// 獲取檔案的副檔名
String ext = FilenameUtils.getExtension(pictureFile
.getOriginalFilename());
// 設定圖片上傳路徑
String url = request.getSession().getServletContext()
.getRealPath("/upload");
System.out.println(url);
// 以絕對路徑儲存重名命後的圖片
pictureFile.transferTo(new File(url + "/" + name + "." + ext));
// 把圖片儲存路徑儲存到資料庫
goods.setGoodsPic("upload/" + name + "." + ext);
String currentAdmin = (String)request.getSession().getAttribute("name");
goods.setUpdateAdmin(currentAdmin);
goods.setGoodsName(goodsName);
goods.setMacId(macId);
boolean updateGoods = goodsService.updateGoods(goods);
System.out.println(updateGoods);
return "redirect:goodsStock.do";
}
這裡重點要關注的就兩點,一個是實體類物件Goods和一個MultipartFile ,這倆是提交資料時不能少的