ajaxfileupload传递文件及参数

本文介绍如何使用ajaxfileupload插件实现文件的无刷新上传,并在上传过程中加入额外文本参数的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                                                                 ajaxfileupload带参数上传文件

        最经在工作中要实现文件的无刷新上传,当然XmlHttpRequest对象是无法实现文件的上传功能的。google后找到JQuery的fileupload插件,此插件通过一个IFrame并在IFrame中创建一个form表单来实现文件上传;而在我的应用中还需要带一些其他的文本参数,而此插件并未提供此功能。 
        既然是动态创建form表单,那么更定能加入其他参数的,请看代码(注意第41行): 

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


使用方法: 
Java代码   收藏代码
  1. $.ajaxFileUpload({  
  2.         url: '/ajax/mine/uploadLogo',  
  3.         secureuri:false,  
  4.         fileElementId:'input_logo',  
  5.         dataType: 'json',  
  6.         data: {//加入的文本参数  
  7.             "logoPath""param1",  
  8.             "logoName""param2"  
  9.         },  
  10.         success: function(data) {  
  11.               
  12.         },  
  13.         error: function() {  
  14.             showError("上传失败,请检查文件是否符合格式要求。");  
  15.               
  16.         }  
  17.           
  18.     });  

最后注意服务器返回的response type必须是text/html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值