1、使用ajaxfileupload.js的插件,但是對插件做了一處修改,才能夠正常使用
修改的部分如下:
1 2 uploadHttpData: function (r, type) { 3 var data = !type; 4 data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context 5 if (type == "script") 6 jQuery.globalEval(data); // Get the JavaScript object, if JSON is used. 7 if (type == "json"){//對json類型的返回結果,做截取處理 8 var tempData = data.substring(data.indexOf(">\"") + 2); 9 data = tempData.replace("\"</pre>", ""); 10 } 11 if (type == "html") 12 jQuery("<div>").html(data).evalScripts(); 13 return data; 14 }
2、檢查文件大小,對於常用瀏覽器測試都是可以的...
3、使用struts的action接收,兩個參數:1)上傳到文件imageFile;2)上傳的本地文件路徑imageFilePath
4、ajaxfileupload.js源碼在最后貼出來
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <script src="jquery1.8/jquery-1.8.0.js" type="text/javascript"></script> 6 <script src="ajaxfileupload.js"></script> 7 <script type="text/javascript"> 8 9 /* 頭像上傳 */ 10 function ajaxfileupload() { 11 var filepath = $("#imageFile").val(); 12 //檢查是否為圖片 13 if(!isImage(filepath)){ 14 return false; 15 } 16 //檢查文件大小,不能超過2M 17 if(!checkFileSize(filepath)){ 18 return false; 19 } 20 21 $.ajaxFileUpload({ 22 url: 'stu/uploadimage', 23 secureuri: false, //一般設置為false 24 type: 'post', 25 data: {imageFileName: $("#imageFile").val()}, 26 dataType: 'json', 27 fileElementId: "imageFile", 28 success: function (data, status) { 29 if (data == "error") { 30 alert("上傳失敗,請重試"); 31 } else { 32 //導航欄:頭像 33 $("#header_student_image").attr("src", data); 34 alert("上傳成功"); 35 } 36 }, 37 error: function (data, status, e)//服務器響應失敗處理函數 38 { 39 alert("上傳失敗,請重試"); 40 } 41 } 42 ); 43 return false; 44 }; 45 46 /* 檢查是否為圖片 */ 47 function isImage(filepath) { 48 var extStart = filepath.lastIndexOf("."); 49 var ext = filepath.substring(extStart, filepath.length).toUpperCase(); 50 if (ext != ".BMP" && ext != ".PNG" && ext != ".GIF" && ext != ".JPG" && ext != ".JPEG") { 51 alert("頭像只能是bmp,png,gif,jpeg,jpg格式喔"); 52 return false; 53 } 54 return true; 55 } 56 57 /* 檢查圖片大小,不能超過3M,支持IE、filefox、chrome */ 58 function checkFileSize(filepath) { 59 var maxsize = 2 * 1024 * 1024;//2M 60 var errMsg = "上傳的頭像文件不能超過2M喔!!!"; 61 var tipMsg = "您的瀏覽器暫不支持上傳頭像,確保上傳文件不要超過2M,建議使用IE、FireFox、Chrome瀏覽器。"; 62 63 try { 64 var filesize = 0; 65 var ua = window.navigator.userAgent; 66 if (ua.indexOf("MSIE") >= 1) { 67 //IE 68 var img = new Image(); 69 img.src = filepath; 70 filesize = img.fileSize; 71 } else { 72 //file_size = document.getElementById("imageFile").files[0].size; 73 filesize = $("#imageFile")[0].files[0].size; //byte 74 } 75 76 if (filesize > 0 && filesize > maxsize) { 77 alert(errMsg); 78 return false; 79 } else if (filesize == -1) { 80 alert(tipMsg); 81 return false; 82 } 83 } catch (e) { 84 alert("頭像上傳失敗,請重試"); 85 return false; 86 } 87 return true; 88 } 89 </script> 90 <title>test:上傳頭像</title> 91 </head> 92 <body> 93 <table width="500" cellspacing="0" cellpadding="0"> 94 <tr> 95 <td width="72" id="fileType"> 96 </td> 97 <td width="242"> 98 <img id="image_url" src="" class="wetalkimg"/> 99 <input type="file" id="imageFile" name="imageFile" onchange="ajaxfileupload(this);"/> 100 </td> 101 </tr> 102 </table> 103 </body> 104 </html
5、ajaxfileupload.js源碼
1 jQuery.extend({ 2 createUploadIframe: function (id, uri) {//id為當前系統時間字符串,uri是外部傳入的json對象的一個參數 3 //create frame 4 var frameId = 'jUploadFrame' + id; //給iframe添加一個獨一無二的id 5 var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; //創建iframe元素 6 if (window.ActiveXObject) {//判斷瀏覽器是否支持ActiveX控件 7 if (typeof uri == 'boolean') { 8 iframeHtml += ' src="' + 'javascript:false' + '"'; 9 } else if (typeof uri == 'string') { 10 iframeHtml += ' src="' + uri + '"'; 11 } 12 } 13 iframeHtml += ' />'; 14 jQuery(iframeHtml).appendTo(document.body); //將動態iframe追加到body中 15 return jQuery('#' + frameId).get(0); //返回iframe對象 16 }, 17 createUploadForm: function (id, fileElementId, data) {//id為當前系統時間字符串,fileElementId為頁面<input type='file' />的id,data的值需要根據傳入json的鍵來決定 18 //create form 19 var formId = 'jUploadForm' + id; //給form添加一個獨一無二的id 20 var fileId = 'jUploadFile' + id; //給<input type='file' />添加一個獨一無二的id 21 var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //創建form元素 22 if (data) {//通常為false 23 for (var i in data) { 24 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //根據data的內容,創建隱藏域,這部分我還不知道是什么時候用到。估計是傳入json的時候,如果默認傳一些參數的話要用到。 25 } 26 } var oldElement = jQuery('#' + fileElementId); //得到頁面中的<input type='file' />對象 27 var newElement = jQuery(oldElement).clone(); //克隆頁面中的<input type='file' />對象 28 jQuery(oldElement).attr('id', fileId); //修改原對象的id 29 jQuery(oldElement).before(newElement); //在原對象前插入克隆對象 30 jQuery(oldElement).appendTo(form); //把原對象插入到動態form的結尾處 31 //set attributes 32 jQuery(form).css('position', 'absolute'); //給動態form添加樣式,使其浮動起來, 33 jQuery(form).css('top', '-1200px'); 34 jQuery(form).css('left', '-1200px'); 35 jQuery(form).appendTo('body'); //把動態form插入到body中 36 return form; 37 }, 38 ajaxFileUpload: function (s) {//這里s是個json對象,傳入一些ajax的參數 39 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout 40 s = jQuery.extend({}, jQuery.ajaxSettings, s); //此時的s對象是由jQuery.ajaxSettings和原s對象擴展后的對象 41 var id = new Date().getTime(); //取當前系統時間,目的是得到一個獨一無二的數字 42 var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //創建動態form 43 var io = jQuery.createUploadIframe(id, s.secureuri); //創建動態iframe 44 var frameId = 'jUploadFrame' + id; //動態iframe的id 45 var formId = 'jUploadForm' + id; //動態form的id 46 // Watch for a new set of requests 47 if (s.global && !jQuery.active++) {//當jQuery開始一個ajax請求時發生 48 jQuery.event.trigger("ajaxStart"); //觸發ajaxStart方法 49 } var requestDone = false; //請求完成標志 50 // Create the request object 51 var xml = {}; if (s.global) 52 jQuery.event.trigger("ajaxSend", [xml, s]); //觸發ajaxSend方法 53 // Wait for a response to come back 54 var uploadCallback = function (isTimeout) {//回調函數 55 var io = document.getElementById(frameId); //得到iframe對象 56 try { if (io.contentWindow) {//動態iframe所在窗口對象是否存在 57 xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null; 58 xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document; 59 } else if (io.contentDocument) {//動態iframe的文檔對象是否存在 60 xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null; 61 xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document; 62 } 63 } catch (e) { 64 jQuery.handleError(s, xml, null, e); 65 } if (xml || isTimeout == "timeout") {//xml變量被賦值或者isTimeout == "timeout"都表示請求發出,並且有響應 66 requestDone = true; //請求完成 67 var status; try { 68 status = isTimeout != "timeout" ? "success" : "error"; //如果不是“超時”,表示請求成功 69 // Make sure that the request was successful or notmodified 70 if (status != "error") { // process the data (runs the xml through httpData regardless of callback) 71 var data = jQuery.uploadHttpData(xml, s.dataType); //根據傳送的type類型,返回json對象,此時返回的data就是后台操作后的返回結果 72 // If a local callback was specified, fire it and pass it the data 73 if (s.success) 74 s.success(data, status); //執行上傳成功的操作 75 // Fire the global callback 76 if (s.global) 77 jQuery.event.trigger("ajaxSuccess", [xml, s]); 78 } else 79 jQuery.handleError(s, xml, status); 80 } catch (e) { 81 status = "error"; 82 jQuery.handleError(s, xml, status, e); 83 } // The request was completed 84 if (s.global) 85 jQuery.event.trigger("ajaxComplete", [xml, s]); // Handle the global AJAX counter 86 if (s.global && ! --jQuery.active) 87 jQuery.event.trigger("ajaxStop"); // Process result 88 if (s.complete) 89 s.complete(xml, status); 90 jQuery(io).unbind();//移除iframe的事件處理程序 91 setTimeout(function () {//設置超時時間 92 try { 93 jQuery(io).remove();//移除動態iframe 94 jQuery(form).remove();//移除動態form 95 } catch (e) { 96 jQuery.handleError(s, xml, null, e); 97 } 98 }, 100) 99 xml = null 100 } 101 } // Timeout checker 102 if (s.timeout > 0) {//超時檢測 103 setTimeout(function () { // Check to see if the request is still happening 104 if (!requestDone) uploadCallback("timeout");//如果請求仍未完成,就發送超時信號 105 }, s.timeout); 106 } try { var form = jQuery('#' + formId); 107 jQuery(form).attr('action', s.url);//傳入的ajax頁面導向url 108 jQuery(form).attr('method', 'POST');//設置提交表單方式 109 jQuery(form).attr('target', frameId);//返回的目標iframe,就是創建的動態iframe 110 if (form.encoding) {//選擇編碼方式 111 jQuery(form).attr('encoding', 'multipart/form-data'); 112 } else { 113 jQuery(form).attr('enctype', 'multipart/form-data'); 114 } 115 jQuery(form).submit();//提交form表單 116 } catch (e) { 117 jQuery.handleError(s, xml, null, e); 118 } 119 jQuery('#' + frameId).load(uploadCallback); //ajax 請求從服務器加載數據,同時傳入回調函數 120 return { abort: function () { } }; 121 }, 122 uploadHttpData: function (r, type) { 123 var data = !type; 124 data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context 125 if (type == "script") 126 jQuery.globalEval(data); // Get the JavaScript object, if JSON is used. 127 if (type == "json"){//修改之處 128 var tempData = data.substring(data.indexOf(">\"") + 2); 129 data = tempData.replace("\"</pre>", ""); 130 } 131 if (type == "html") 132 jQuery("<div>").html(data).evalScripts(); 133 return data; 134 }, 135 handleError: function (s, xhr, status, e) { 136 if (s.error) { 137 s.error.call(s.context || s, xhr, status, e); 138 } 139 if (s.global) { 140 (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]); 141 } 142 } 143 })