最经在工作中要实现文件的无刷新上传,当然XmlHttpRequest对象是无法实现文件的上传功能的。google后找到JQuery的fileupload插件,此插件通过一个IFrame并在IFrame中创建一个form表单来实现文件上传;而在我的应用中还需要带一些其他的文本参数,而此插件并未提供此功能。
既然是动态创建form表单,那么更定能加入其他参数的,请看代码(注意第41行):
使用方法:
最后注意服务器返回的response type必须是text/html
原文链接:https://www.f2er.com/ajax/165676.html既然是动态创建form表单,那么更定能加入其他参数的,请看代码(注意第41行):
- jQuery.extend({
- createUploadIframe:function(id,uri)
- {
- //createframe
- varframeId='jUploadFrame'+id;
- if(window.ActiveXObject){
- vario=document.createElement('<iframeid="'+frameId+'"name="'+frameId+'"/>');
- if(typeofuri=='boolean'){
- io.src='javascript:false';
- }
- elseif(typeofuri=='string'){
- io.src=uri;
- else{
- vario=document.createElement('iframe');
- io.id=frameId;
- io.name=frameId;
- io.style.position='absolute';
- io.style.top='-1000px';
- io.style.left='-1000px';
- document.body.appendChild(io);
- returnio
- },
- createUploadForm:function(id,fileElementId,data)
- //createform
- varformId='jUploadForm'+id;
- varfileId='jUploadFile'+id;
- varform=$('<formaction=""method="POST"name="'+formId+'"id="'+formId+'"enctype="multipart/form-data"></form>');
- varoldElement=$('#'+fileElementId);
- varnewElement=$(oldElement).clone();
- $(oldElement).attr('id',fileId);
- $(oldElement).before(newElement);
- $(oldElement).appendTo(form);
- //增加文本参数的支持
- if(data){
- for(variindata){
- $('<inputtype="hidden"name="'+i+'"value="'+data[i]+'"/>').appendTo(form);
- //setattributes
- $(form).css('position','absolute');
- $(form).css('top','-1200px');
- $(form).css('left',250); line-height:18px"> $(form).appendTo('body');
- returnform;
- ajaxFileUpload:function(s){
- //TODOintroduceglobalsettings,allowingtheclienttomodifythemforallrequests,notonlytimeout
- s=jQuery.extend({},jQuery.ajaxSettings,s);
- varid=newDate().getTime()
- varform=jQuery.createUploadForm(id,s.fileElementId,s.data);
- vario=jQuery.createUploadIframe(id,s.secureuri);
- //Watchforanewsetofrequests
- if(s.global&&!jQuery.active++)
- jQuery.event.trigger("ajaxStart");
- varrequestDone=false;
- //Createtherequestobject
- varxml={}
- if(s.global)
- jQuery.event.trigger("ajaxSend",[xml,s]);
- //Waitforaresponsetocomeback
- varuploadCallback=function(isTimeout)
- vario=document.getElementById(frameId);
- try
- if(io.contentWindow)
- 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;
- }if(io.contentDocument)
- xml.responseText=io.contentDocument.document.body?io.contentDocument.document.body.innerHTML: 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")
- requestDone=true;
- varstatus;
- try{
- status=isTimeout!="timeout"?"success":"error";
- //Makesurethattherequestwassuccessfulornotmodified
- if(status!="error")
- //processthedata(runsthexmlthroughhttpDataregardlessofcallback)
- vardata=jQuery.uploadHttpData(xml,s.dataType);
- //Ifalocalcallbackwasspecified,fireitandpassitthedata
- if(s.success)
- s.success(data,status);
- //Firetheglobalcallback
- jQuery.event.trigger("ajaxSuccess",85); font-weight:bold">else
- status="error";
- //Therequestwascompleted
- jQuery.event.trigger("ajaxComplete",0); padding:0px; margin:0px; width:auto; border:0px">//HandletheglobalAJAXcounter
- if(s.global&&!--jQuery.active)
- jQuery.event.trigger("ajaxStop");
- //Processresult
- if(s.complete)
- s.complete(xml,250); line-height:18px"> jQuery(io).unbind()
- setTimeout(function()
- { $(io).remove();
- $(form).remove();
- 100)
- xml=null
- //Timeoutchecker
- if(s.timeout>0)
- setTimeout(function(){
- //Checktoseeiftherequestisstillhappening
- if(!requestDone)uploadCallback("timeout");
- //vario=$('#'+frameId);
- varform=$('#'+formId);
- $(form).attr('action',s.url);
- $(form).attr('method','POST');
- $(form).attr('target',frameId);
- if(form.encoding)
- form.encoding='multipart/form-data';
- form.enctype='multipart/form-data';
- $(form).submit();
- if(window.attachEvent){
- document.getElementById(frameId).attachEvent('onload',uploadCallback);
- document.getElementById(frameId).addEventListener('load',uploadCallback,85); font-weight:bold">false);
- return{abort:function(){}};
- uploadHttpData:function(r,type){
- vardata=!type;
- data=type=="xml"||data?r.responseXML:r.responseText;
- //Ifthetypeis"script",evalitinglobalcontext
- if(type=="script")
- jQuery.globalEval(data);
- //GettheJavaScriptobject,ifJSONisused.
- if(type=="json")
- eval("data="+data);
- //evaluatescriptswithinhtml
- if(type=="html")
- jQuery("<div>").html(data).evalScripts();
- //alert($('param',data).each(function(){alert($(this).attr('value'));}));
- returndata;
- })
使用方法:
$.ajaxFileUpload({
url:'/ajax/mine/uploadlogo',250); line-height:18px"> secureuri:false,250); line-height:18px"> fileElementId:'input_logo',250); line-height:18px"> dataType:'json',250); line-height:18px"> data:{//加入的文本参数
"logoPath":"param1",250); line-height:18px"> "logoName":"param2"
success:function(data){
error:function(){
showError("上传失败,请检查文件是否符合格式要求。");
});
最后注意服务器返回的response type必须是text/html