现在的位置: 首页 > 综合 > 正文

jquery异步上传文件

2017年10月05日 ⁄ 综合 ⁄ 共 9914字 ⁄ 字号 评论关闭

一、创建input元素

[html] view
plain
copy

  1. <input type="file" id="fileToUpload" name="fileToUpload" value="浏览"/>  


二、导入jquery.js和ajaxfileupload.js文件

[javascript] view
plain
copy

  1. jQuery.extend({  
  2.       
  3.   
  4.     createUploadIframe: function(id, uri)  
  5.     {  
  6.             //create frame  
  7.             var frameId = 'jUploadFrame' + id;  
  8.             var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';  
  9.             if(window.ActiveXObject)  
  10.             {  
  11.                 if(typeof uri== 'boolean'){  
  12.                     iframeHtml += ' src="' + 'javascript:false' + '"';  
  13.   
  14.                 }  
  15.                 else if(typeof uri== 'string'){  
  16.                     iframeHtml += ' src="' + uri + '"';  
  17.   
  18.                 }     
  19.             }  
  20.             iframeHtml += ' />';  
  21.             jQuery(iframeHtml).appendTo(document.body);  
  22.   
  23.             return jQuery('#' + frameId).get(0);              
  24.     },  
  25.   
  26.     createUploadForm: function(id, fileElementId, data)  
  27.     {  
  28.         //create form     
  29.         var formId = 'jUploadForm' + id;  
  30.         var fileId = 'jUploadFile' + id;  
  31.         var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');      
  32.         if(data)  
  33.         {  
  34.             for(var i in data)  
  35.             {  
  36.                 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);  
  37.             }             
  38.         }         
  39.         var oldElement = jQuery('#' + fileElementId);  
  40.         var newElement = jQuery(oldElement).clone();  
  41.         jQuery(oldElement).attr('id', fileId);  
  42.         jQuery(oldElement).before(newElement);  
  43.         jQuery(oldElement).appendTo(form);  
  44.   
  45.   
  46.           
  47.         //set attributes  
  48.         jQuery(form).css('position''absolute');  
  49.         jQuery(form).css('top''-1200px');  
  50.         jQuery(form).css('left''-1200px');  
  51.         jQuery(form).appendTo('body');        
  52.         return form;  
  53.     },  
  54.   
  55.     ajaxFileUpload: function(s) {  
  56.         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout          
  57.         s = jQuery.extend({}, jQuery.ajaxSettings, s);  
  58.         var id = new Date().getTime();  
  59.         var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));  
  60.         var io = jQuery.createUploadIframe(id, s.secureuri);  
  61.         var frameId = 'jUploadFrame' + id;  
  62.         var formId = 'jUploadForm' + id;          
  63.         // Watch for a new set of requests  
  64.         if ( s.global && ! jQuery.active++ )  
  65.         {  
  66.             jQuery.event.trigger( "ajaxStart" );  
  67.         }              
  68.         var requestDone = false;  
  69.         // Create the request object  
  70.         var xml = {};   
  71.         if ( s.global )  
  72.             jQuery.event.trigger("ajaxSend", [xml, s]);  
  73.         // Wait for a response to come back  
  74.         var uploadCallback = function(isTimeout)  
  75.         {             
  76.             var io = document.getElementById(frameId);  
  77.             try   
  78.             {                 
  79.                 if(io.contentWindow)  
  80.                 {  
  81.                      xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;  
  82.                      xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;  
  83.                        
  84.                 }else if(io.contentDocument)  
  85.                 {  
  86.                      xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;  
  87.                     xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;  
  88.                 }                         
  89.             }catch(e)  
  90.             {  
  91.                 jQuery.handleError(s, xml, null, e);  
  92.             }  
  93.             if ( xml || isTimeout == "timeout")   
  94.             {                 
  95.                 requestDone = true;  
  96.                 var status;  
  97.                 try {  
  98.                     status = isTimeout != "timeout" ? "success" : "error";  
  99.                     // Make sure that the request was successful or notmodified  
  100.                     if ( status != "error" )  
  101.                     {  
  102.                         // process the data (runs the xml through httpData regardless of callback)  
  103.                         var data = jQuery.uploadHttpData( xml, s.dataType );      
  104.                         // If a local callback was specified, fire it and pass it the data  
  105.                         if ( s.success )  
  106.                             s.success( data, status );  
  107.       
  108.                         // Fire the global callback  
  109.                         if( s.global )  
  110.                             jQuery.event.trigger( "ajaxSuccess", [xml, s] );  
  111.                     } else  
  112.                         jQuery.handleError(s, xml, status);  
  113.                 } catch(e)   
  114.                 {  
  115.                     status = "error";  
  116.                     jQuery.handleError(s, xml, status, e);  
  117.                 }  
  118.   
  119.                 // The request was completed  
  120.                 if( s.global )  
  121.                     jQuery.event.trigger( "ajaxComplete", [xml, s] );  
  122.   
  123.                 // Handle the global AJAX counter  
  124.                 if ( s.global && ! --jQuery.active )  
  125.                     jQuery.event.trigger( "ajaxStop" );  
  126.   
  127.                 // Process result  
  128.                 if ( s.complete )  
  129.                     s.complete(xml, status);  
  130.   
  131.                 jQuery(io).unbind();  
  132.   
  133.                 setTimeout(function()  
  134.                                     {   try   
  135.                                         {  
  136.                                             jQuery(io).remove();  
  137.                                             jQuery(form).remove();    
  138.                                               
  139.                                         } catch(e)   
  140.                                         {  
  141.                                             jQuery.handleError(s, xml, null, e);  
  142.                                         }                                     
  143.   
  144.                                     }, 100);  
  145.   
  146.                 xml = null;  
  147.   
  148.             }  
  149.         };  
  150. // Timeout checker  
  151.         if ( s.timeout > 0 )   
  152.         {  
  153.             setTimeout(function(){  
  154.                 // Check to see if the request is still happening  
  155.                 if( !requestDone ) uploadCallback( "timeout" );  
  156.             }, s.timeout);  
  157.         }  
  158.         try   
  159.         {  
  160.   
  161.             var form = jQuery('#' + formId);  
  162.             jQuery(form).attr('action', s.url);  
  163.             jQuery(form).attr('method''POST');  
  164.             jQuery(form).attr('target', frameId);  
  165.             if(form.encoding)  
  166.             {  
  167.                 jQuery(form).attr('encoding''multipart/form-data');                 
  168.             }  
  169.             else  
  170.             {     
  171.                 jQuery(form).attr('enctype''multipart/form-data');              
  172.             }             
  173.             jQuery(form).submit();  
  174.   
  175.         } catch(e)   
  176.         {             
  177.             jQuery.handleError(s, xml, null, e);  
  178.         }  
  179.           
  180.         jQuery('#' + frameId).load(uploadCallback   );  
  181.         return {abort: function () {}};   
  182.   
  183.     },  
  184.   
  185.     uploadHttpData: function( r, type ) {  
  186.         var data = !type;  
  187.         data = type == "xml" || data ? r.responseXML : r.responseText;  
  188.         // If the type is "script", eval it in global context  
  189.         if ( type == "script" )  
  190.             jQuery.globalEval( data );  
  191.         // Get the JavaScript object, if JSON is used.  
  192.         if ( type == "json" ) {  
  193.             if(data.indexOf('<pre') != -1) {  
  194.                 //此段代码时为了兼容火狐和chrome浏览器  
  195. var newDiv = jQuery(document.createElement("div"));  
  196.                 newDiv.html(data);  
  197.                 data = $("pre:first", newDiv).html();  
  198.  }    
  199.             eval( "data = " + data );  
  200.         }  
  201.         // evaluate scripts within html  
  202.         if ( type == "html" )  
  203.             jQuery("<div>").html(data).evalScripts();  
  204.         return data;  
  205.     }  
  206. });  

注意:在ajaxfileupload中会用到jquery的handleError函数,但是此函数在1.4.2之后不存在了,所有如果用到更高的

版本需要复制进去

三、写调用代码

[javascript] view
plain
copy

  1. function uploadImage() {  
  2.     $.ajaxFileUpload({  
  3.         url: 'photo/upload',//需要链接到服务器地址  
  4.         secureuri:false,  
  5.         fileElementId: 'fileToUpload',//文件选择框的id属性  
  6.         dataType:'json',//服务器返回的格式,可以是json  
  7.         success: function (data){  
  8.             if (data['result'] == 1) {  
  9.                   
  10.             }  
  11.         },  
  12.         error: function(data){  
  13.         }  
  14.     });  
  15. }  


四、写后台处理代码:

[java] view
plain
copy

  1. List items = super.getUploadFileItems(req);//使用fileupolad组件获取request中的参数  
  2.                 HashMap<String, String> params = super.getUploadParams(items);  
  3.                 Iterator iter = items.iterator();  
  4.                 FileItem fileItem = null;  
  5.                 while (iter.hasNext()) {  
  6.                     FileItem item = (FileItem) iter.next();  
  7.                     if (!item.isFormField()) {  
  8.                         fileItem = item;  
  9.                         break;  
  10.                     }  
  11.                 }  
  12.                 byte[] imageContent = null;  
  13.                 String suffix = null;  
  14.                 if (fileItem != null) {  
  15.                     imageContent = IOTools.readContent(  
  16.                             fileItem.getInputStream(), 4096);  
  17.                     suffix = fileItem.getContentType();  
  18.                 }  


注意:

(1)如果服务端想返回json格式,一定不能加上response.setContentType("application/json");

 否则IE和opera会解析成文件下载,或者写成response.setContentType("text/html");

结合strut2是result节点中也要设置contentType,否则浏览器总是提示将返回的JSON结果另存为文件,不会交给ajaxfileupload处理。

这是因为struts2 JSON Plugin默认的contentType为application/json,而ajaxfileupload则要求为text/html。

(2)返回url赋值给img的src时,记得加上时间戳或者保证url不重复,否则会被浏览器缓存,导致无法实时看到图片

转自:http://blog.csdn.net/mrliu20082009/article/details/7220203

抱歉!评论已关闭.