上傳圖片前端js代碼如下:
var MEimgFile = $("#MEimg")[0].files[0];
var MEimgForm = new FormData();
MEimgForm.append("file", MEimgFile);
var xhr = new XMLHttpRequest();
xhr.open("post", FileServlet, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var resultJson = $.parseJSON(xhr.responseText);
if (resultJson.code == 1) {
MEimgUrl = resultJson.imgUrl;
$("#feedbackMEimg").html('');
$("#feedbackMEimg").html('上傳成功!');
uploadMEimgpositiveFile();
} else {
$("#feedbackMEimgFile").html('上傳失敗!請稍後重試');
}
}
}
xhr.send(MEimgForm);
這是原生的ajax,下面是用juqery封裝好的ajax。
var MEimgForm = new FormData();
MEimgForm.append("file", MEimgFile);
$.ajax({
type : 'post',
url : 'insertReserveExpertServlet',
data : MEimgForm ,
processData : false,
contentType : false,
async:false,
dataType : 'json',
success : function(result) {
},
error : function(result) {
}
});
如果圖片太大,測試的時候用的3M大小的圖片,用jquery封裝好的ajax就用遇到一種問題。
圖片上傳成功了,但返回函數執行的是error。
百度了一通,說是上傳時間過長導致的,解決方法是修改tomcat的配置文件,記不太清了。
我試了一下,用原生的ajax就不會出現上面那個問題,也就是用第一種方法。
但上傳時候確實挺長的,3M的圖片上傳了12秒,或許可以對圖片進行壓縮,有沒有大神知道更好的方法呀!