介紹
AjaxFileUpload.js 是一個異步上傳文件的jQuery插件,原理是創建隱藏的表單和iframe然后用JS去提交,獲得返回值。
下載地址:
屬性
語法:$.ajaxFileUpload([options]) | |
url | 上傳處理程序地址。 |
fileElementId | 需要上傳的文件域的ID,即<input type="file">的ID。 |
secureuri | 是否啟用安全提交,默認為false。 |
dataType | 服務器返回的數據類型。可以為xml,script,json,html。如果不填寫,jQuery會自動判斷。 |
success | 提交成功后自動執行的處理函數,參數data就是服務器返回的數據。 |
error | 提交失敗自動執行的處理函數。 |
data | 自定義參數。這個東西比較有用,當有數據是與上傳的圖片相關的時候,這個東西就要用到了。 |
type | 當要提交自定義參數時,這個參數要設置成post |
錯誤提示
SyntaxError: missing ; before statement | 如果出現這個錯誤就需要檢查url路徑是否可以訪問 |
SyntaxError: syntax error | 如果出現這個錯誤就需要檢查處理提交操作的服務器后台處理程序是否存在語法錯誤 |
SyntaxError: invalid property id | 如果出現這個錯誤就需要檢查文本域屬性ID是否存在 |
SyntaxError: missing } in XML expression | 如果出現這個錯誤就需要檢查文件name是否一致或不存在 |
Object function (a,b){return new e.fn.init(a,b,h)} has no method 'handleError'(谷歌瀏覽器) | dataType參數一定要大寫。如:dataType: 'HTML' |
jQuery.handleError is not a function | http://zhangzhaoaaa.iteye.com/blog/2123021 |
其它自定義錯誤 | 大家可使用變量$error直接打印的方法檢查各參數是否正確,比起上面這些無效的錯誤提示還是方便很多 |
例子
腳本:
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/js/ajaxfileupload.js"></script> <script> /** * 異步上傳圖片 */ $(function () { $("#saveImg").click(function () { //效驗上傳圖片類型 var ths=$('#fileImg'); if (ths.val().length <= 0) { alert("請上傳圖片"); return false; } else if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(ths.val())){ alert("圖片類型必須是.gif,jpeg,jpg,png中的一種"); ths.val(""); return false; } //效驗成功調用異步上傳函數 ajaxFileUpload(); return true; }) }) /** * ajaxFileUpload JQuery異步上傳插件 */ function ajaxFileUpload() { $.ajaxFileUpload ( { url: realPath+"/whiteListRule/saveImg.htm", //用於文件上傳的服務器端請求地址 type: 'post', data: { gameId: gameId }, secureuri: false, //是否需要安全協議,一般設置為false fileElementId: 'fileImg', //文件上傳域的ID dataType: 'text', //返回值類型 一般設置為json success: function (data, status) //服務器成功響應處理函數 { var data=eval("("+data+")") if (typeof (data.error) != 'undefined') { if (data.error != '') { alert(data.error); } else { alert(data.msg); $("#img1").attr("src", data.imgurl); } } }, error: function (data, status, e)//服務器響應失敗處理函數 { alert(e); } } ) return false; } </script>
控制器:
package com.shiliu.game.controller; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.shiliu.game.common.Constant; import com.shiliu.game.domain.Game; import com.shiliu.game.service.IGameService; import com.shiliu.game.utils.PropertyUtil; import com.shiliu.game.utils.ReadProperties; /** * 異步上傳控制器 * @author wkr * @Date 2016-12-12 * */ @Controller @RequestMapping(value = "/whiteListRule") public class WhiteListRuleController { //log4j private Logger log =Logger.getLogger(AddCustomerDataController.class); //存儲圖片路徑 private String fileUploadPath = PropertyUtil.getProperty("file_upload"); //讀取圖片路徑 private String fileReadPath = PropertyUtil.getProperty("file_url"); @Resource private IGameService gameService; //Game /** * 上傳圖片 * @param gameId 參數 * @param multipart 文件 * @param request * @return */ @RequestMapping(value="/saveImg") @ResponseBody public String saveImgMethod( @RequestParam(value = "gameId") String gameId, @RequestParam(value="fileImg") MultipartFile multipart, HttpServletRequest request ){ String path = null; File upload = null; //已經保存文件的全路徑 String img = null; //存儲數據庫路徑 String readPath = null; //讀取路徑 //返回信息 String msg = ""; String error = ""; try { //存儲路徑 path = fileUploadPath + Constant.FILE_PATH; //存儲本地文件夾 upload = ReadProperties.upload(multipart, path); //存儲數據庫路徑 img = Constant.FILE_PATH + "/" + upload.getName(); //讀取路徑 readPath = fileReadPath + Constant.FILE_PATH + "/" + upload.getName(); //限制圖片大小 int ruleHeight = 400; int ruleWidth = 750; int deviation = 100;//誤差 BufferedImage sourceImg = ImageIO.read(new FileInputStream(upload)); int imgHeight = sourceImg.getHeight();//圖片高 int imgWidth = sourceImg.getWidth();//圖片寬 if (Math.abs(ruleWidth - imgWidth) <= deviation && Math.abs(ruleHeight - imgHeight) <= deviation) { gameService.updateByPrimaryKeySelective(new Game(gameId, img)); msg = "上傳成功!"; }else { error = "圖片不符合規定誤!"; } } catch (Exception e) { error = "文件保存本地失敗!"; log.error("文件保存本地失敗!", e); } String res = "{ error:'" + error + "', msg:'" + msg + "',imgurl:'" + readPath + "'}"; return res; } }
JSP:
<body> <!-- 異步上傳圖片 --> <b>背景圖片(建議圖片大小750Χ400,允許誤差100已內)</b> <br> <img id="img1" alt="上傳成功后顯示圖片" src="${fileUrl }${game.imageUrl1}"> <br> <input id="fileImg" type="file" name="fileImg" size="80" /> <input id="saveImg" type="button" value="上傳圖片" /> </body>
原理分析

jQuery.extend({ createUploadIframe: function (id, uri) {//id為當前系統時間字符串,uri是外部傳入的json對象的一個參數 //create frame var frameId = 'jUploadFrame' + id; //給iframe添加一個獨一無二的id var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; //創建iframe元素 if (window.ActiveXObject) {//判斷瀏覽器是否支持ActiveX控件 if (typeof uri == 'boolean') { iframeHtml += ' src="' + 'javascript:false' + '"'; } else if (typeof uri == 'string') { iframeHtml += ' src="' + uri + '"'; } } iframeHtml += ' />'; jQuery(iframeHtml).appendTo(document.body); //將動態iframe追加到body中 return jQuery('#' + frameId).get(0); //返回iframe對象 }, createUploadForm: function (id, fileElementId, data) {//id為當前系統時間字符串,fileElementId為頁面<input type='file' />的id,data的值需要根據傳入json的鍵來決定 //create form var formId = 'jUploadForm' + id; //給form添加一個獨一無二的id var fileId = 'jUploadFile' + id; //給<input type='file' />添加一個獨一無二的id var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //創建form元素 if (data) {//通常為false for (var i in data) { jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //根據data的內容,創建隱藏域,這部分我還不知道是什么時候用到。估計是傳入json的時候,如果默認傳一些參數的話要用到。 } } var oldElement = jQuery('#' + fileElementId); //得到頁面中的<input type='file' />對象 var newElement = jQuery(oldElement).clone(); //克隆頁面中的<input type='file' />對象 jQuery(oldElement).attr('id', fileId); //修改原對象的id jQuery(oldElement).before(newElement); //在原對象前插入克隆對象 jQuery(oldElement).appendTo(form); //把原對象插入到動態form的結尾處 //set attributes jQuery(form).css('position', 'absolute'); //給動態form添加樣式,使其浮動起來, jQuery(form).css('top', '-1200px'); jQuery(form).css('left', '-1200px'); jQuery(form).appendTo('body'); //把動態form插入到body中 return form; }, ajaxFileUpload: function (s) {//這里s是個json對象,傳入一些ajax的參數 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); //此時的s對象是由jQuery.ajaxSettings和原s對象擴展后的對象 var id = new Date().getTime(); //取當前系統時間,目的是得到一個獨一無二的數字 var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //創建動態form var io = jQuery.createUploadIframe(id, s.secureuri); //創建動態iframe var frameId = 'jUploadFrame' + id; //動態iframe的id var formId = 'jUploadForm' + id; //動態form的id // Watch for a new set of requests if (s.global && !jQuery.active++) {//當jQuery開始一個ajax請求時發生 jQuery.event.trigger("ajaxStart"); //觸發ajaxStart方法 } var requestDone = false; //請求完成標志 // Create the request object var xml = {}; if (s.global) jQuery.event.trigger("ajaxSend", [xml, s]); //觸發ajaxSend方法 // Wait for a response to come back var uploadCallback = function (isTimeout) {//回調函數 var io = document.getElementById(frameId); //得到iframe對象 try { if (io.contentWindow) {//動態iframe所在窗口對象是否存在 xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null; xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document; } else if (io.contentDocument) {//動態iframe的文檔對象是否存在 xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null; xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document; } } catch (e) { jQuery.handleError(s, xml, null, e); } if (xml || isTimeout == "timeout") {//xml變量被賦值或者isTimeout == "timeout"都表示請求發出,並且有響應 requestDone = true; //請求完成 var status; try { status = isTimeout != "timeout" ? "success" : "error"; //如果不是“超時”,表示請求成功 // Make sure that the request was successful or notmodified if (status != "error") { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData(xml, s.dataType); //根據傳送的type類型,返回json對象,此時返回的data就是后台操作后的返回結果 // If a local callback was specified, fire it and pass it the data if (s.success) s.success(data, status); //執行上傳成功的操作 // Fire the global callback if (s.global) jQuery.event.trigger("ajaxSuccess", [xml, s]); } else jQuery.handleError(s, xml, status); } catch (e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if (s.global) jQuery.event.trigger("ajaxComplete", [xml, s]); // Handle the global AJAX counter if (s.global && ! --jQuery.active) jQuery.event.trigger("ajaxStop"); // Process result if (s.complete) s.complete(xml, status); jQuery(io).unbind();//移除iframe的事件處理程序 setTimeout(function () {//設置超時時間 try { jQuery(io).remove();//移除動態iframe jQuery(form).remove();//移除動態form } catch (e) { jQuery.handleError(s, xml, null, e); } }, 100) xml = null } } // Timeout checker if (s.timeout > 0) {//超時檢測 setTimeout(function () { // Check to see if the request is still happening if (!requestDone) uploadCallback("timeout");//如果請求仍未完成,就發送超時信號 }, s.timeout); } try { var form = jQuery('#' + formId); jQuery(form).attr('action', s.url);//傳入的ajax頁面導向url jQuery(form).attr('method', 'POST');//設置提交表單方式 jQuery(form).attr('target', frameId);//返回的目標iframe,就是創建的動態iframe if (form.encoding) {//選擇編碼方式 jQuery(form).attr('encoding', 'multipart/form-data'); } else { jQuery(form).attr('enctype', 'multipart/form-data'); } jQuery(form).submit();//提交form表單 } catch (e) { jQuery.handleError(s, xml, null, e); } jQuery('#' + frameId).load(uploadCallback); //ajax 請求從服務器加載數據,同時傳入回調函數 return { abort: function () { } }; }, uploadHttpData: function (r, type) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if (type == "script") jQuery.globalEval(data); // Get the JavaScript object, if JSON is used. if (type == "json") eval("data = " + data); // evaluate scripts within html if (type == "html") jQuery("<div>").html(data).evalScripts(); return data; } })

$.ajaxFileUpload ( { url: '../../XXXX/XXXX.aspx', //用於文件上傳的服務器端請求地址 secureuri: false, //一般設置為false fileElementId: $("input#xxx").attr("id"), //文件上傳控件的id屬性 <input type="file" id="file" name="file" /> 注意,這里一定要有name值 //$("form").serialize(),表單序列化。指把所有元素的ID,NAME 等全部發過去 dataType: 'json',//返回值類型 一般設置為json complete: function () {//只要完成即執行,最后執行 }, success: function (data, status) //服務器成功響應處理函數 { if (typeof (data.error) != 'undefined') { if (data.error != '') { if (data.error == "1001") {//這個error(錯誤碼)是由自己定義的,根據后台返回的json對象的鍵值而判斷 } else if (data.error == "1002") { } alert(data.msg);//同error return; } else { alert(data.msg); } } /* * 這里就是做一些其他操作,比如把圖片顯示到某控件中去之類的。 */ }, error: function (data, status, e)//服務器響應失敗處理函數 { alert(e); } } )