ajax異步上傳
定義Form
<form id="ff" enctype="multipart/form-data">
<input type="text" name="name"><br>
<input type="file" name="source"><img height="21px" id="sig"/><br>
<input type="button" value="上傳" onclick="upload();">
</form>
<img id="img"/>
定義ajax異步上傳邏輯
function upload(){
//準備上傳:顯示進度條
document.getElementById("sig").src="/static/app_ajax/load.gif";
//創建xhr
xhr = new XMLHttpRequest();
xhr.open("post","/ajax/up_logic/");
//設置監聽:獲取文件上傳進度
xhr.upload.onprogress=function(a){//文件上傳過程中不斷觸發
console.log(a.loaded);
console.log(a.total);
if(a.loaded == a.total)
document.getElementById("sig").src="/static/app_ajax/ok.gif";
};
//設置監聽:獲取響應內容【重點】
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
ret = xhr.responseText //接受響應內容:圖片在服務器的存儲位置(訪問路徑)
console.log(ret)
//回顯上傳的圖片
document.getElementById("img").src="/static/"+ret;
}
}
//FomrData(form的dom對象)
xhr.send(new FormData(document.forms[0])) //發送請求,攜帶form的所有數據
}
定義Controller,接受上傳的文件
方式照舊
補充:client可以通過jquery提供的方法$.ajax()完成上傳
$.ajax({type:"post",
data:new FormData(document.getElementById("ff")),//ff表示表單的id
url:"xxx",
success:function(a){
document.getElementById("img").src="/static/"+a
},
processData: false,//禁止編碼請求參數
contentType: false //不設置請求頭
}
)
$.ajax({xhr:function(){
var xhr = $.ajaxSettings.xhr();//獲取當前的xhr
xhr.upload.onprogress=function(p){
if(p.loaded==p.total)
console.log("上傳完成")
}
return xhr;
}
type:"post",
data:new FormData(document.getElementById("ff")),
url:"xxx",
success:function(a){
document.getElementById("img").src="/static/"+a
},
processData: false,#禁止編碼請求參數
contentType: false #不設置請求頭
}
)