Ajax引用 ajaxfileupload.js 進行文件上傳


第一次寫博客還真有點激動中帶有意思彷徨,哈哈哈 有什么不足的請多多指教

這個應該是我目前用過的除了框架之外最好用的文件上傳 ”工具“ 了,不說廢話直接看代碼

首先引入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                 if (data[i] instanceof Array) {
 25                     for ( var j in data[i]) {
 26                         jQuery('<input type="checkbox" name="'+i+'" value="'+data[i][j]+'" checked />').appendTo(form);
 27                     }
 28                 } else {
 29                     jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //根據data的內容,創建隱藏域,這部分我還不知道是什么時候用到。估計是傳入json的時候,如果默認傳一些參數的話要用到。  
 30                 }
 31             }  
 32         }
 33         if (fileElementId instanceof Array) {
 34             for (var i = 0; i < fileElementId.length; i++) {
 35                 var oldElement = jQuery('#' + fileElementId[i]); //得到頁面中的<input type='file' />對象  
 36                 var newElement = jQuery(oldElement).clone(); //克隆頁面中的<input type='file' />對象  
 37                 jQuery(oldElement).attr('id', fileElementId[i]); //修改原對象的id  
 38                 jQuery(oldElement).before(newElement); //在原對象前插入克隆對象  
 39                 jQuery(oldElement).appendTo(form); //把原
 40             }
 41         } else {
 42             var oldElement = jQuery('#' + fileElementId); //得到頁面中的<input type='file' />對象  
 43             var newElement = jQuery(oldElement).clone(); //克隆頁面中的<input type='file' />對象  
 44             jQuery(oldElement).attr('id', fileId); //修改原對象的id  
 45             jQuery(oldElement).before(newElement); //在原對象前插入克隆對象  
 46             jQuery(oldElement).appendTo(form); //把原對象插入到動態form的結尾處  
 47         }
 48 
 49         //set attributes  
 50         jQuery(form).css('position', 'absolute'); //給動態form添加樣式,使其浮動起來,  
 51         jQuery(form).css('top', '-1200px');  
 52         jQuery(form).css('left', '-1200px');  
 53         jQuery(form).appendTo('body'); //把動態form插入到body中  
 54         return form;  
 55     },  
 56     ajaxFileUpload: function (s) {//這里s是個json對象,傳入一些ajax的參數  
 57         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout          
 58         s = jQuery.extend({}, jQuery.ajaxSettings, s); //此時的s對象是由jQuery.ajaxSettings和原s對象擴展后的對象  
 59         var id = new Date().getTime(); //取當前系統時間,目的是得到一個獨一無二的數字  
 60         var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //創建動態form  
 61         var io = jQuery.createUploadIframe(id, s.secureuri); //創建動態iframe  
 62         var frameId = 'jUploadFrame' + id; //動態iframe的id  
 63         var formId = 'jUploadForm' + id; //動態form的id  
 64         // Watch for a new set of requests  
 65         if (s.global && !jQuery.active++) {//當jQuery開始一個ajax請求時發生  
 66             jQuery.event.trigger("ajaxStart"); //觸發ajaxStart方法  
 67         }        var requestDone = false; //請求完成標志  
 68         // Create the request object  
 69         var xml = {};        if (s.global)  
 70             jQuery.event.trigger("ajaxSend", [xml, s]); //觸發ajaxSend方法  
 71         // Wait for a response to come back  
 72         var uploadCallback = function (isTimeout) {//回調函數  
 73             var io = document.getElementById(frameId); //得到iframe對象  
 74             try {                if (io.contentWindow) {//動態iframe所在窗口對象是否存在  
 75                     xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;  
 76                     xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;  
 77                 } else if (io.contentDocument) {//動態iframe的文檔對象是否存在  
 78                     xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;  
 79                     xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;  
 80                 }  
 81             } catch (e) {  
 82                 jQuery.handleError(s, xml, null, e);  
 83             }            if (xml || isTimeout == "timeout") {//xml變量被賦值或者isTimeout == "timeout"都表示請求發出,並且有響應  
 84                 requestDone = true; //請求完成  
 85                 var status;                try {  
 86                     status = isTimeout != "timeout" ? "success" : "error"; //如果不是“超時”,表示請求成功  
 87                     // Make sure that the request was successful or notmodified  
 88                     if (status != "error") {                        // process the data (runs the xml through httpData regardless of callback)  
 89                         var data = jQuery.uploadHttpData(xml, s.dataType); //根據傳送的type類型,返回json對象,此時返回的data就是后台操作后的返回結果  
 90                         // If a local callback was specified, fire it and pass it the data  
 91                         if (s.success)  
 92                             s.success(data, status); //執行上傳成功的操作  
 93                         // Fire the global callback  
 94                         if (s.global)  
 95                             jQuery.event.trigger("ajaxSuccess", [xml, s]);  
 96                     } else  
 97                         jQuery.handleError(s, xml, status);  
 98                 } catch (e) {  
 99                     status = "error";  
100                     jQuery.handleError(s, xml, status, e);  
101                 }                // The request was completed  
102                 if (s.global)  
103                     jQuery.event.trigger("ajaxComplete", [xml, s]);                // Handle the global AJAX counter  
104                 if (s.global && ! --jQuery.active)  
105                     jQuery.event.trigger("ajaxStop");                // Process result  
106                 if (s.complete)  
107                     s.complete(xml, status);  
108                 jQuery(io).unbind();//移除iframe的事件處理程序  
109                 setTimeout(function () {//設置超時時間  
110                     try {  
111                         jQuery(io).remove();//移除動態iframe  
112                         jQuery(form).remove();//移除動態form  
113                     } catch (e) {  
114                         jQuery.handleError(s, xml, null, e);  
115                     }  
116                 }, 100)  
117                 xml = null  
118             }  
119         }        // Timeout checker  
120         if (s.timeout > 0) {//超時檢測  
121             setTimeout(function () {                // Check to see if the request is still happening  
122                 if (!requestDone) uploadCallback("timeout");//如果請求仍未完成,就發送超時信號  
123             }, s.timeout);  
124         }        try {            var form = jQuery('#' + formId);  
125             jQuery(form).attr('action', s.url);//傳入的ajax頁面導向url  
126             jQuery(form).attr('method', 'POST');//設置提交表單方式  
127             jQuery(form).attr('target', frameId);//返回的目標iframe,就是創建的動態iframe  
128             if (form.encoding) {//選擇編碼方式  
129                 jQuery(form).attr('encoding', 'multipart/form-data');  
130             }            else {  
131                 jQuery(form).attr('enctype', 'multipart/form-data');  
132             }  
133             jQuery(form).submit();//提交form表單  
134         } catch (e) {  
135             jQuery.handleError(s, xml, null, e);  
136         }  
137         jQuery('#' + frameId).load(uploadCallback); //ajax 請求從服務器加載數據,同時傳入回調函數  
138         return { abort: function () { } };  
139     },  
140     uploadHttpData: function (r, type) {        var data = !type;  
141         data = type == "xml" || data ? r.responseXML : r.responseText;        // If the type is "script", eval it in global context  
142         if (type == "script")  
143             jQuery.globalEval(data);        // Get the JavaScript object, if JSON is used.  
144         if (type == "json")  
145             data=data.replace("<pre>","").replace("</pre>","");//除去字符串中的pre標簽
146             data=eval('(' + data+ ')');        // evaluate scripts within html  
147             return data;
148         if (type == "html")  
149             jQuery("<div>").html(data).evalScripts();        return data;  
150     },
151     //自添加方法handleError
152     handleError: function( s, xhr, status, e )      {
153         // If a local callback was specified, fire it
154         if ( s.error ) {
155             s.error.call( s.context || s, xhr, status, e );
156         }
157         // Fire the global callback
158         if ( s.global ) {
159             (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
160         }
161     }
162 }) 

接下來就是上傳文件操作了 ,我上傳的是圖片可以多圖上傳哦

function uploadAgree(obj){
         var f=$(obj).val();
         if(f == null || f ==undefined || f == ''){
             return false;
         }else if(!/\.(?:png|jpg|bmp|gif|PNG|JPG|BMP|GIF)$/.test(f)){
             alert("類型必須是圖片(.png|jpg|bmp|gif|PNG|JPG|BMP|GIF)");
             $(obj).val('');
             return false;
         }else{
            //批量上傳圖片
             $.ajaxFileUpload({
                  url:"/uploadPictureList",//需要鏈接到服務器地址   
                   secureuri:false,  
                   fileElementId:"uploadagree",//文件選擇框的id屬性  ,//文件選擇框的id屬性  
                   dataType: 'json',   //json 
                   contentType: false,    //不可缺
                  processData: false,    //不可缺
                 success: function (data){
                     if(data!=null){
                         $.each(data,function(i,url){
                            //拼接圖片列表 
                              var id = $('#detailImgs li:last').attr('id');
                                  id = id.substr(1);
                                  id = parseInt(id) + 1;
                                  var ids=id;
                                  id = 'P'+id;                                                    
                              var a_hidden="<li style='width:100px;height:100px;margin-right:5px;' id='"+ id +"'><input type='hidden' value='"+url+"' name='imgs'>";
                              var img_html="<img style='width:100%;height:100%'  src='"+url+"'  onclick='showOriginal(this)' original='"+url+"'>";
                              var a_html="<a class='del_img_a' href='javascript:void(0);' onclick='delespan1("+ids+")'>刪除</a>";
                              var li_html="</li>";
                              var length_=$('#detailImgs').find("li").length;
                              if(length_<6){
                                  $('#detailImgs').append(a_hidden+img_html+a_html+li_html);
                              }else{
                                  alert("最多添加5張圖片");
                                  return false;
                              }
                         });
                         
                     }else{
                         alert("上傳失敗");
                         $("#url").val("");
                         $(obj).val('');
                     }                   
                 },
                 error:function(XMLHttpRequest, textStatus, errorThrown){  
                     alert("上傳失敗,請檢查網絡后重試");
                     $("#url").val("");
                     $(obj).val('');
                } 
             });
         }
    }
    //上傳之后刪除
    function delespan1(id){
           $('#P'+id).remove();
    }

HTML 代碼:

 <div style="height:200px;margin:20px;;">
     <input type="hidden" id="employ_id"/>
     <input type="file" name="file" id="uploadagree" multiple="multiple" onchange="uploadAgree(this)"/>
     <ul id="detailImgs" style="overflow: hidden;margin-top:20px;">
         <li style="display:none;" id="P0">                                       
     </ul>
 </div>

后台接收controller層代碼:

 1 @RequestMapping("/uploadPictureList")
 2     @ResponseBody
 3     public String uploadPictureList(@RequestParam(value="file",required=false)MultipartFile[] file,HttpServletRequest request) {
 4         
 5          File targetFile=null;
 6             String msg="";//返回存儲路徑
 7             int code=1;
 8             List imgList=new ArrayList();
 9             if (file!=null && file.length>0) {
10                 for (int i = 0; i < file.length; i++) {
11                     String fileName=file[i].getOriginalFilename();//獲取文件名加后綴
12                    // String paths="/upload/hr/employee/";
13                     if(fileName!=null&&fileName!=""){   
14                         String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/upload/hr/employee/";//存儲路徑
15                         String path = request.getSession().getServletContext().getRealPath("/upload/hr/employee/"); //文件存儲位置
16                         String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后綴
17                         fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名
18 
19                         //先判斷文件是否存在
20                         File file1 =new File(path); 
21                         //如果文件夾不存在則創建    
22                         if(!file1 .exists()  && !file1 .isDirectory()){       
23                             file1 .mkdir();  
24                         }
25                         targetFile = new File(file1, fileName);
26                         try {
27                             file[i].transferTo(targetFile);
28                            // msg=returnUrl+fileName;
29                             msg="/upload/hr/employee/"+fileName;
30                             imgList.add(msg);
31                         } catch (Exception e) {
32                             e.printStackTrace();
33                         }
34                     }
35                 }
36             }               
37      return JSON.toJSONString(imgList);
38     }

到這里就基本完成了!!!

 

--------------------------------請多多指教


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM