jQuery+Ajax實現圖片的預覽和上傳
1、配置Spring-web.xml
<!-- springmvc上傳圖片 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
2、引用jQuery的插件ajaxFileUpload.js
地址:
https://github.com/carlcarl/AjaxFileUpload
https://github.com/carlcarl/AjaxFileUpload/blob/master/ajaxfileupload.js
在線引用一直沒有效,就直接下載放到js文件夾中。
3、jsp代碼
<div >
<label >點擊圖片即可修改</label><br>
<img id="headPic" src="/market/images/image.png" width="150px" height="150px" style="padding: 5px">
<input id="upload" name="file" accept="image/*" type="file" style="display: none"/>
<button id="submit_btn" type="submit">確定修改</button>
</div>
4、js代碼
$(function() {
//頭像預覽
$("#headPic").click(function () {
$("#upload").click(); //隱藏了input:file樣式后,點擊頭像就可以本地上傳
$("#upload").on("change",function(){
var objUrl = getObjectURL(this.files[0]) ; //獲取圖片的路徑,該路徑不是圖片在本地的路徑
if (objUrl) {
$("#headPic").attr("src", objUrl) ; //將圖片路徑存入src中,顯示出圖片
}
});
});
//圖片上傳
$("#submit_btn").click(function () {
var imgurl = document.getElementById("upload").value;
$.ajaxFileUpload({
url:"uploadHeadPic",
fileElementId: "upload", //文件上傳域的ID,這里是input的ID,而不是img的
dataType: 'json', //返回值類型 一般設置為json
contentType: "application/x-www-form-urlencoded; charset=utf-8",
success: function (data) {
alert(data.code+" "+ data.msg);
if (data.code==200){
$("#headPic").attr("src","/market/images/image.png");
//將圖片換成默認的+圖片
}
=
}
});
});
});
//建立一個可存取到該file的url
function getObjectURL(file) {
var url = null ;
if (window.createObjectURL!=undefined) { // basic
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
5、后台java代碼
@RequestMapping(value = "/uploadHeadPic"
, method = RequestMethod.POST
, produces = "application/json; charset=utf-8")
@ResponseBody
public Object uploadHeadPic(@RequestParam() MultipartFile file, HttpServletRequest request) {
//在這里面文件存儲的方案一般是:收到文件→獲取文件名→在本地存儲目錄建立防重名文件→寫入文件→返回成功信息
//如果上面的步驟中在結束前任意一步失敗,那就直接失敗了。
FileOutputStream out=null;
if (null == file || file.isEmpty()) {
responseObj = new ResponseObj();
responseObj.setCode(400);
responseObj.setMsg("文件不能為空");
}else{
responseObj = new ResponseObj();
responseObj.setCode(200);
responseObj.setMsg("文件上傳成功");
//這里以用戶ID作為文件夾
int uid = (Integer) request.getSession().getAttribute("userid");
//創建一個文件夾,網上代碼很多
String url = new FileUtil().createImageDir( String.valueOf(uid));
try {
//獲得二進制流並輸出
byte[] f = file.getBytes();
out = new FileOutputStream(url+file.getOriginalFilename());
out.write(f);
} catch (IOException e) {
System.out.println("上傳失敗");
responseObj.setCode(500);
responseObj.setMsg("文件保存失敗");
}finally {
// 完畢,關閉所有鏈接
try {
out.close();
} catch (IOException e) {
System.out.println("關閉流失敗");
}
}
}
return new GsonUtil().CollectionToJson(responseObj);
}
//在獲得file后,打印下面信息 System.out.println(file.getContentType()); System.out.println(file.getOriginalFilename()); System.out.println(file.getName()); image/png //input配置的 accept="image/*" clipboard.png //上傳的圖片名 file //這個flie是input的name屬性決定
現在有個問題是,在上傳圖片后,第二次點擊上傳,這時上傳的圖片依舊是之前的值,嘗試多種清空input的file值也沒有用。
以下方法都不行
var file = doucment.getElementById('file');
//1
file.value = ''; //雖然file的value不能設為有字符的值,但是可以設置為空值
//2
file.outerHTML = file.outerHTML; //重新初始化了file的html
//3
var obj = document.getElementById('fileupload') ;
obj.select();
document.selection.clear();
--------------------- 作者:HYeeee 來源:CSDN 原文:https://blog.csdn.net/hyeeee/article/details/78594907?utm_source=copy 版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

