Ajax上传文件怎样才能分块上传呢?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax上传文件怎样才能分块上传呢?相关的知识,希望对你有一定的参考价值。
需要向后台发送每个分段块的偏移量和大小两个参数,offset跟length,求一个具体示例代码。
参考技术A 用 File API 可以获得需上传的档案,用 FileReader 获得 ArrayBuffer 后可以切开,然后用 FormData 上传切开的二元数据 (及任何额外数据例如 offset)。你还得把它们在伺服器拼接,并应付中途出错,例如在上载逾时的时候清除之前上载的部分,并在客户端试图恢复上载时通知它逾时了。 (例如说,电脑在上载中途休眠或断电的情况)使用 jQuery 的文件上传进度条
【中文标题】使用 jQuery 的文件上传进度条【英文标题】:File upload progress bar with jQuery 【发布时间】:2013-03-02 20:39:19 【问题描述】:我正在尝试在我的项目中实现 AJAX 文件上传功能。我为此使用 jQuery;我的代码使用 AJAX 提交数据。我还想实现一个文件上传进度条。我怎样才能做到这一点?有什么方法可以计算已经上传了多少,以便我可以计算上传的百分比并创建进度条?
【问题讨论】:
你看过 jQuery 插件或 jQuery UI 吗? jqueryui.com/progressbar 你看过plugin homepage上的例子吗? 查看 jQuery 插件 Uploadify。 见***.com/questions/28856729/… 【参考方案1】:我只用 jQuery 完成了这个:
$.ajax(
xhr: function()
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt)
if (evt.lengthComputable)
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
console.log(percentComplete);
if (percentComplete === 100)
, false);
return xhr;
,
url: posturlfile,
type: "POST",
data: JSON.stringify(fileuploaddata),
contentType: "application/json",
dataType: "json",
success: function(result)
console.log(result);
);
【讨论】:
这样更好,因为它不需要 jQuery.ajaxForm。仅与 jQuery 核心库完美配合。 这是这里唯一真正的答案。 (y) 如何获取fileuploaddata
?
这完全是客户端的。这显示了客户端上传的数据量,而不是服务器接收到的数据量。因此,请务必仅在完整的 ajax 请求结束后显示最终的“成功”消息。
***.com/questions/6974684/… 这是关于如何获取fileuploaddata
。【参考方案2】:
注意:本题与jQuery form plugin有关。如果您正在寻找纯 jQuery 解决方案,start here。 没有适用于所有浏览器的整体 jQuery 解决方案。所以你必须使用插件。我正在使用dropzone.js,它可以轻松地回退旧版浏览器。您喜欢哪个插件取决于您的需求。那里有很多很好的比较帖子。
来自examples:
jQuery:
$(function()
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm(
beforeSend: function()
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
,
uploadProgress: function(event, position, total, percentComplete)
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
,
complete: function(xhr)
status.html(xhr.responseText);
);
);
html:
<form action="file-echo2.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
您必须使用 css 设置进度条的样式...
【讨论】:
我使用了“uploadProgress”并使用了 jquery-ui 进度条。谢谢 您好 Jam,我实现了您的代码,但收到 500 个内部服务器错误。 听起来您的 PHP 代码有错误。你的 file-echo2.php 长什么样子? 这可能是 jquery.malsup.com/form/#getting-started 但不是直接与 Jquery @Lem:你说得对,这段代码来自 malsup (jquery.malsup.com/form/progress.html) 使用 Form Plugin 的演示【参考方案3】:我在我的项目中使用了以下内容。 你也可以试试。
ajax = new XMLHttpRequest();
ajax.onreadystatechange = function ()
if (ajax.status)
if (ajax.status == 200 && (ajax.readyState == 4))
//To do tasks if any, when upload is completed
ajax.upload.addEventListener("progress", function (event)
var percent = (event.loaded / event.total) * 100;
//**percent** variable can be used for modifying the length of your progress bar.
console.log(percent);
);
ajax.open("POST", 'your file upload link', true);
ajax.send(formData);
//ajax.send is for uploading form data.
【讨论】:
【参考方案4】:看看这个:http://hayageek.com/docs/jquery-upload-file.php 无意中在网上找到的。
【讨论】:
【参考方案5】:如果你在项目中使用jquery,并且不想从头实现上传机制,可以使用https://github.com/blueimp/jQuery-File-Upload。
他们有一个非常好的 api,具有多个文件选择、拖放支持、进度条、验证和预览图像、跨域支持、分块和可恢复的文件上传。他们有多种服务器语言(node、php、python 和 go)的示例脚本。
演示网址:https://blueimp.github.io/jQuery-File-Upload/.
【讨论】:
我无法使用 PHP 配置该插件。你知道怎么做吗?【参考方案6】:这是一个看起来更完整的 jquery 1.11.x $.ajax() 用法:
<script type="text/javascript">
function uploadProgressHandler(event)
$("#loaded_n_total").html("Uploaded " + event.loaded + " bytes of " + event.total);
var percent = (event.loaded / event.total) * 100;
var progress = Math.round(percent);
$("#uploadProgressBar").html(progress + " percent na ang progress");
$("#uploadProgressBar").css("width", progress + "%");
$("#status").html(progress + "% uploaded... please wait");
function loadHandler(event)
$("#status").html(event.target.responseText);
$("#uploadProgressBar").css("width", "0%");
function errorHandler(event)
$("#status").html("Upload Failed");
function abortHandler(event)
$("#status").html("Upload Aborted");
$("#uploadFile").click(function (event)
event.preventDefault();
var file = $("#fileUpload")[0].files[0];
var formData = new FormData();
formData.append("file1", file);
$.ajax(
url: 'http://testarea.local/UploadWithProgressBar1/file_upload_parser.php',
method: 'POST',
type: 'POST',
data: formData,
contentType: false,
processData: false,
xhr: function ()
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress",
uploadProgressHandler,
false
);
xhr.addEventListener("load", loadHandler, false);
xhr.addEventListener("error", errorHandler, false);
xhr.addEventListener("abort", abortHandler, false);
return xhr;
);
);
</script>
【讨论】:
我试过你的代码 xhr: function() var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("进度", uploadProgressHandler, false );但不是在调用我的函数【参考方案7】:这解决了我的问题
var url = "http://localhost/tech1/index.php?route=app/upload/ajax";
$.ajax(
xhr: function()
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt)
if (evt.lengthComputable)
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
var $link = $('.'+ids);
var $img = $link.find('i');
$link.html('Uploading..('+percentComplete+'%)');
$link.append($img);
, false);
return xhr;
,
url: url,
type: "POST",
data: JSON.stringify(uploaddata),
contentType: "application/json",
dataType: "json",
success: function(result)
console.log(result);
);
【讨论】:
复制/粘贴卡西尔的答案,基本上【参考方案8】:Kathir's answer 很棒,因为他只用 jQuery 就解决了这个问题。 我只是想在他的答案中添加一些内容,以便使用漂亮的 HTML 进度条来处理他的代码:
$.ajax(
xhr: function()
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt)
if (evt.lengthComputable)
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.progress-bar').width(percentComplete+'%');
$('.progress-bar').html(percentComplete+'%');
, false);
return xhr;
,
url: posturlfile,
type: "POST",
data: JSON.stringify(fileuploaddata),
contentType: "application/json",
dataType: "json",
success: function(result)
console.log(result);
);
这是进度条的HTML代码,我使用Bootstrap 3作为进度条元素:
<div class="progress" style="display:none;">
<div class="progress-bar progress-bar-success progress-bar-striped
active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style="width:0%">
0%
</div>
</div>
【讨论】:
【参考方案9】:JavaScript:
<script>
/* jquery.form.min.js */
(function(e)"use strict";if(typeof define==="function"&&define.amd)define(["jquery"],e)elsee(typeof jQuery!="undefined"?jQuery:window.Zepto))(function(e)"use strict";function r(t)var n=t.data;if(!t.isDefaultPrevented())t.preventDefault();e(t.target).ajaxSubmit(n)function i(t)var n=t.target;var r=e(n);if(!r.is("[type=submit],[type=image]"))var i=r.closest("[type=submit]");if(i.length===0)returnn=i[0]var s=this;s.clk=n;if(n.type=="image")if(t.offsetX!==undefined)s.clk_x=t.offsetX;s.clk_y=t.offsetYelse if(typeof e.fn.offset=="function")var o=r.offset();s.clk_x=t.pageX-o.left;s.clk_y=t.pageY-o.topelses.clk_x=t.pageX-n.offsetLeft;s.clk_y=t.pageY-n.offsetTopsetTimeout(function()s.clk=s.clk_x=s.clk_y=null,100)function s()if(!e.fn.ajaxSubmit.debug)returnvar t="[jquery.form] "+Array.prototype.join.call(arguments,"");if(window.console&&window.console.log)window.console.log(t)else if(window.opera&&window.opera.postError)window.opera.postError(t)var t=;t.fileapi=e("<input type='file'/>").get(0).files!==undefined;t.formdata=window.FormData!==undefined;var n=!!e.fn.prop;e.fn.attr2=function()if(!n)return this.attr.apply(this,arguments)var e=this.prop.apply(this,arguments);if(e&&e.jquery||typeof e==="string")return ereturn this.attr.apply(this,arguments);e.fn.ajaxSubmit=function(r)function k(t)var n=e.param(t,r.traditional).split("&");var i=n.length;var s=[];var o,u;for(o=0;o<i;o++)n[o]=n[o].replace(/\+/g," ");u=n[o].split("=");s.push([decodeURIComponent(u[0]),decodeURIComponent(u[1])])return sfunction L(t)var n=new FormData;for(var s=0;s<t.length;s++)n.append(t[s].name,t[s].value)if(r.extraData)var o=k(r.extraData);for(s=0;s<o.length;s++)if(o[s])n.append(o[s][0],o[s][1])r.data=null;var u=e.extend(true,,e.ajaxSettings,r,contentType:false,processData:false,cache:false,type:i||"POST");if(r.uploadProgress)u.xhr=function()var t=e.ajaxSettings.xhr();if(t.upload)t.upload.addEventListener("progress",function(e)var t=0;var n=e.loaded||e.position;var i=e.total;if(e.lengthComputable)t=Math.ceil(n/i*100)r.uploadProgress(e,n,i,t),false)return tu.data=null;var a=u.beforeSend;u.beforeSend=function(e,t)if(r.formData)t.data=r.formDataelset.data=nif(a)a.call(this,e,t);return e.ajax(u)function A(t)function T(e)var t=null;tryif(e.contentWindow)t=e.contentWindow.documentcatch(n)s("cannot get iframe.contentWindow document: "+n)if(t)return ttryt=e.contentDocument?e.contentDocument:e.documentcatch(n)s("cannot get iframe.contentDocument: "+n);t=e.documentreturn tfunction k()function f()tryvar e=T(v).readyState;s("state = "+e);if(e&&e.toLowerCase()=="uninitialized")setTimeout(f,50)catch(t)s("Server abort: ",t," (",t.name,")");_(x);if(w)clearTimeout(w)w=undefinedvar t=a.attr2("target"),n=a.attr2("action"),r="multipart/form-data",u=a.attr("enctype")||a.attr("encoding")||r;o.setAttribute("target",p);if(!i||/post/i.test(i))o.setAttribute("method","POST")if(n!=l.url)o.setAttribute("action",l.url)if(!l.skipEncodingOverride&&(!i||/post/i.test(i)))a.attr(encoding:"multipart/form-data",enctype:"multipart/form-data")if(l.timeout)w=setTimeout(function()b=true;_(S),l.timeout)var c=[];tryif(l.extraData)for(var h in l.extraData)if(l.extraData.hasOwnProperty(h))if(e.isPlainObject(l.extraData[h])&&l.extraData[h].hasOwnProperty("name")&&l.extraData[h].hasOwnProperty("value"))c.push(e('<input type="hidden" name="'+l.extraData[h].name+'">').val(l.extraData[h].value).appendTo(o)[0])elsec.push(e('<input type="hidden" name="'+h+'">').val(l.extraData[h]).appendTo(o)[0])if(!l.iframeTarget)d.appendTo("body")if(v.attachEvent)v.attachEvent("onload",_)elsev.addEventListener("load",_,false)setTimeout(f,15);tryo.submit()catch(m)var g=document.createElement("form").submit;g.apply(o)finallyo.setAttribute("action",n);o.setAttribute("enctype",u);if(t)o.setAttribute("target",t)elsea.removeAttr("target")e(c).remove()function _(t)if(m.aborted||M)returnA=T(v);if(!A)s("cannot access response document");t=xif(t===S&&m)m.abort("timeout");E.reject(m,"timeout");returnelse if(t==x&&m)m.abort("server abort");E.reject(m,"error","server abort");returnif(!A||A.location.href==l.iframeSrc)if(!b)returnif(v.detachEvent)v.detachEvent("onload",_)elsev.removeEventListener("load",_,false)var n="success",r;tryif(b)throw"timeout"var i=l.dataType=="xml"||A.XMLDocument||e.isXMLDoc(A);s("isXml="+i);if(!i&&window.opera&&(A.body===null||!A.body.innerHTML))if(--O)s("requeing onLoad callback, DOM not available");setTimeout(_,250);returnvar o=A.body?A.body:A.documentElement;m.responseText=o?o.innerHTML:null;m.responseXML=A.XMLDocument?A.XMLDocument:A;if(i)l.dataType="xml"m.getResponseHeader=function(e)var t="content-type":l.dataType;return t[e.toLowerCase()];if(o)m.status=Number(o.getAttribute("status"))||m.status;m.statusText=o.getAttribute("statusText")||m.statusTextvar u=(l.dataType||"").toLowerCase();var a=/(json|script|text)/.test(u);if(a||l.textarea)var f=A.getElementsByTagName("textarea")[0];if(f)m.responseText=f.value;m.status=Number(f.getAttribute("status"))||m.status;m.statusText=f.getAttribute("statusText")||m.statusTextelse if(a)var c=A.getElementsByTagName("pre")[0];var p=A.getElementsByTagName("body")[0];if(c)m.responseText=c.textContent?c.textContent:c.innerTextelse if(p)m.responseText=p.textContent?p.textContent:p.innerTextelse if(u=="xml"&&!m.responseXML&&m.responseText)m.responseXML=D(m.responseText)tryL=H(m,u,l)catch(g)n="parsererror";m.error=r=g||ncatch(g)s("error caught: ",g);n="error";m.error=r=g||nif(m.aborted)s("upload aborted");n=nullif(m.status)n=m.status>=200&&m.status<300||m.status===304?"success":"error"if(n==="success")if(l.success)l.success.call(l.context,L,"success",m)E.resolve(m.responseText,"success",m);if(h)e.event.trigger("ajaxSuccess",[m,l])else if(n)if(r===undefined)r=m.statusTextif(l.error)l.error.call(l.context,m,n,r)E.reject(m,"error",r);if(h)e.event.trigger("ajaxError",[m,l,r])if(h)e.event.trigger("ajaxComplete",[m,l])if(h&&!--e.active)e.event.trigger("ajaxStop")if(l.complete)l.complete.call(l.context,m,n)M=true;if(l.timeout)clearTimeout(w)setTimeout(function()if(!l.iframeTarget)d.remove()elsed.attr("src",l.iframeSrc)m.responseXML=null,100)var o=a[0],u,f,l,h,p,d,v,m,g,y,b,w;var E=e.Deferred();E.abort=function(e)m.abort(e);if(t)for(f=0;f<c.length;f++)u=e(c[f]);if(n)u.prop("disabled",false)elseu.removeAttr("disabled")l=e.extend(true,,e.ajaxSettings,r);l.context=l.context||l;p="jqFormIO"+(new Date).getTime();if(l.iframeTarget)d=e(l.iframeTarget);y=d.attr2("name");if(!y)d.attr2("name",p)elsep=yelsed=e('<iframe name="'+p+'" src="'+l.iframeSrc+'" />');d.css(position:"absolute",top:"-1000px",left:"-1000px")v=d[0];m=aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(),getResponseHeader:function(),setRequestHeader:function(),abort:function(t)var n=t==="timeout"?"timeout":"aborted";s("aborting upload... "+n);this.aborted=1;tryif(v.contentWindow.document.execCommand)v.contentWindow.document.execCommand("Stop")catch(r)d.attr("src",l.iframeSrc);m.error=n;if(l.error)l.error.call(l.context,m,n,t)if(h)e.event.trigger("ajaxError",[m,l,n])if(l.complete)l.complete.call(l.context,m,n);h=l.global;if(h&&0===e.active++)e.event.trigger("ajaxStart")if(h)e.event.trigger("ajaxSend",[m,l])if(l.beforeSend&&l.beforeSend.call(l.context,m,l)===false)if(l.global)e.active--E.reject();return Eif(m.aborted)E.reject();return Eg=o.clk;if(g)y=g.name;if(y&&!g.disabled)l.extraData=l.extraData||;l.extraData[y]=g.value;if(g.type=="image")l.extraData[y+".x"]=o.clk_x;l.extraData[y+".y"]=o.clk_yvar S=1;var x=2;var N=e("meta[name=csrf-token]").attr("content");var C=e("meta[name=csrf-param]").attr("content");if(C&&N)l.extraData=l.extraData||;l.extraData[C]=Nif(l.forceSync)k()elsesetTimeout(k,10)var L,A,O=50,M;var D=e.parseXML||function(e,t)if(window.ActiveXObject)t=new ActiveXObject("Microsoft.XMLDOM");t.async="false";t.loadXML(e)elset=(new DOMParser).parseFromString(e,"text/xml")return t&&t.documentElement&&t.documentElement.nodeName!="parsererror"?t:null;var P=e.parseJSON||function(e)return window["eval"]("("+e+")");var H=function(t,n,r)var i=t.getResponseHeader("content-type")||"",s=n==="xml"||!n&&i.indexOf("xml")>=0,o=s?t.responseXML:t.responseText;if(s&&o.documentElement.nodeName==="parsererror")if(e.error)e.error("parsererror")if(r&&r.dataFilter)o=r.dataFilter(o,n)if(typeof o==="string")if(n==="json"||!n&&i.indexOf("json")>=0)o=P(o)else if(n==="script"||!n&&i.indexOf("javascript")>=0)e.globalEval(o)return o;return Eif(!this.length)s("ajaxSubmit: skipping submit process - no element selected");return thisvar i,o,u,a=this;if(typeof r=="function")r=success:relse if(r===undefined)r=i=r.type||this.attr2("method");o=r.url||this.attr2("action");u=typeof o==="string"?e.trim(o):"";u=u||window.location.href||"";if(u)u=(u.match(/^([^#]+)/)||[])[1]r=e.extend(true,url:u,success:e.ajaxSettings.success,type:i||e.ajaxSettings.type,iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank",r);var f=;this.trigger("form-pre-serialize",[this,r,f]);if(f.veto)s("ajaxSubmit: submit vetoed via form-pre-serialize trigger");return thisif(r.beforeSerialize&&r.beforeSerialize(this,r)===false)s("ajaxSubmit: submit aborted via beforeSerialize callback");return thisvar l=r.traditional;if(l===undefined)l=e.ajaxSettings.traditionalvar c=[];var h,p=this.formToArray(r.semantic,c);if(r.data)r.extraData=r.data;h=e.param(r.data,l)if(r.beforeSubmit&&r.beforeSubmit(p,this,r)===false)s("ajaxSubmit: submit aborted via beforeSubmit callback");return thisthis.trigger("form-submit-validate",[p,this,r,f]);if(f.veto)s("ajaxSubmit: submit vetoed via form-submit-validate trigger");return thisvar d=e.param(p,l);if(h)d=d?d+"&"+h:hif(r.type.toUpperCase()=="GET")r.url+=(r.url.indexOf("?")>=0?"&":"?")+d;r.data=nullelser.data=dvar v=[];if(r.resetForm)v.push(function()a.resetForm())if(r.clearForm)v.push(function()a.clearForm(r.includeHidden))if(!r.dataType&&r.target)var m=r.success||function();v.push(function(t)var n=r.replaceTarget?"replaceWith":"html";e(r.target)[n](t).each(m,arguments))else if(r.success)v.push(r.success)r.success=function(e,t,n)var i=r.context||this;for(var s=0,o=v.length;s<o;s++)v[s].apply(i,[e,t,n||a,a]);if(r.error)var g=r.error;r.error=function(e,t,n)var i=r.context||this;g.apply(i,[e,t,n,a])if(r.complete)var y=r.complete;r.complete=function(e,t)var n=r.context||this;y.apply(n,[e,t,a])var b=e("input[type=file]:enabled",this).filter(function()return e(this).val()!=="");var w=b.length>0;var E="multipart/form-data";var S=a.attr("enctype")==E||a.attr("encoding")==E;var x=t.fileapi&&t.formdata;s("fileAPI :"+x);var T=(w||S)&&!x;var N;if(r.iframe!==false&&(r.iframe||T))if(r.closeKeepAlive)e.get(r.closeKeepAlive,function()N=A(p))elseN=A(p)else if((w||S)&&x)N=L(p)elseN=e.ajax(r)a.removeData("jqxhr").data("jqxhr",N);for(var C=0;C<c.length;C++)c[C]=nullthis.trigger("form-submit-notify",[this,r]);return this;e.fn.ajaxForm=function(t)t=t||;t.delegation=t.delegation&&e.isFunction(e.fn.on);if(!t.delegation&&this.length===0)var n=s:this.selector,c:this.context;if(!e.isReady&&n.s)s("DOM not ready, queuing ajaxForm");e(function()e(n.s,n.c).ajaxForm(t));return thiss("terminating; zero elements found by selector"+(e.isReady?"":" (DOM not ready)"));return thisif(t.delegation)e(document).off("submit.form-plugin",this.selector,r).off("click.form-plugin",this.selector,i).on("submit.form-plugin",this.selector,t,r).on("click.form-plugin",this.selector,t,i);return thisreturn this.ajaxFormUnbind().bind("submit.form-plugin",t,r).bind("click.form-plugin",t,i);e.fn.ajaxFormUnbind=function()return this.unbind("submit.form-plugin click.form-plugin");e.fn.formToArray=function(n,r)var i=[];if(this.length===0)return ivar s=this[0];var o=this.attr("id");var u=n?s.getElementsByTagName("*"):s.elements;var a;if(u&&!/MSIE [678]/.test(navigator.userAgent))u=e(u).get()if(o)a=e(':input[form="'+o+'"]').get();if(a.length)u=(u||[]).concat(a)if(!u||!u.length)return ivar f,l,c,h,p,d,v;for(f=0,d=u.length;f<d;f++)p=u[f];c=p.name;if(!c||p.disabled)continueif(n&&s.clk&&p.type=="image")if(s.clk==p)i.push(name:c,value:e(p).val(),type:p.type);i.push(name:c+".x",value:s.clk_x,name:c+".y",value:s.clk_y)continueh=e.fieldValue(p,true);if(h&&h.constructor==Array)if(r)r.push(p)for(l=0,v=h.length;l<v;l++)i.push(name:c,value:h[l])else if(t.fileapi&&p.type=="file")if(r)r.push(p)var m=p.files;if(m.length)for(l=0;l<m.length;l++)i.push(name:c,value:m[l],type:p.type)elsei.push(name:c,value:"",type:p.type)else if(h!==null&&typeof h!="undefined")if(r)r.push(p)i.push(name:c,value:h,type:p.type,required:p.required)if(!n&&s.clk)var g=e(s.clk),y=g[0];c=y.name;if(c&&!y.disabled&&y.type=="image")i.push(name:c,value:g.val());i.push(name:c+".x",value:s.clk_x,name:c+".y",value:s.clk_y)return i;e.fn.formSerialize=function(t)return e.param(this.formToArray(t));e.fn.fieldSerialize=function(t)var n=[];this.each(function()var r=this.name;if(!r)returnvar i=e.fieldValue(this,t);if(i&&i.constructor==Array)for(var s=0,o=i.length;s<o;s++)n.push(name:r,value:i[s])else if(i!==null&&typeof i!="undefined")n.push(name:this.name,value:i));return e.param(n);e.fn.fieldValue=function(t)for(var n=[],r=0,i=this.length;r<i;r++)var s=this[r];var o=e.fieldValue(s,t);if(o===null||typeof o=="undefined"||o.constructor==Array&&!o.length)continueif(o.constructor==Array)e.merge(n,o)elsen.push(o)return n;e.fieldValue=function(t,n)var r=t.name,i=t.type,s=t.tagName.toLowerCase();if(n===undefined)n=trueif(n&&(!r||t.disabled||i=="reset"||i=="button"||(i=="checkbox"||i=="radio")&&!t.checked||(i=="submit"||i=="image")&&t.form&&t.form.clk!=t||s=="select"&&t.selectedIndex==-1))return nullif(s=="select")var o=t.selectedIndex;if(o<0)return nullvar u=[],a=t.options;var f=i=="select-one";var l=f?o+1:a.length;for(var c=f?o:0;c<l;c++)var h=a[c];if(h.selected)var p=h.value;if(!p)p=h.attributes&&h.attributes.value&&!h.attributes.value.specified?h.text:h.valueif(f)return pu.push(p)return ureturn e(t).val();e.fn.clearForm=function(t)return this.each(function()e("input,select,textarea",this).clearFields(t));e.fn.clearFields=e.fn.clearInputs=function(t)var n=/^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;return this.each(function()var r=this.type,i=this.tagName.toLowerCase();if(n.test(r)||i=="textarea")this.value=""else if(r=="checkbox"||r=="radio")this.checked=falseelse if(i=="select")this.selectedIndex=-1else if(r=="file")if(/MSIE/.test(navigator.userAgent))e(this).replaceWith(e(this).clone(true))elsee(this).val("")else if(t)if(t===true&&/hidden/.test(r)||typeof t=="string"&&e(this).is(t))this.value="");e.fn.resetForm=function()return this.each(function()if(typeof this.reset=="function"||typeof this.reset=="object"&&!this.reset.nodeType)this.reset());e.fn.enable=function(e)if(e===undefined)e=truereturn this.each(function()this.disabled=!e);e.fn.selected=function(t)if(t===undefined)t=truereturn this.each(function()var n=this.type;if(n=="checkbox"||n=="radio")this.checked=telse if(this.tagName.toLowerCase()=="option")var r=e(this).parent("select");if(t&&r[0]&&r[0].type=="select-one")r.find("option").selected(false)this.selected=t);e.fn.ajaxSubmit.debug=false)
</script>
<script type="text/javascript">
$(document).ready(function ()
$('#myform').on('change', '.wpcf7-file', function (e)
e.preventDefault();
var myParent = $(this).parent();
var filname= $('input[type=file]').val()
if (filname)
$(this).parent().find('#progress-div').show();
$('#myform').ajaxSubmit(
// target: '#progress-div123',/**********only for response************/
beforeSubmit: function ()
myParent.find('#progress-bar').width('0%');
,
uploadProgress: function (event, position, total, percentComplete)
myParent.find('#progress-bar').width(percentComplete + '%');
myParent.find('#progress-bar').html('<div id="progress-status">' + percentComplete + ' %</div>')
,
success: function showResponse(responseText, statusText, xhr, $form)
//myParent.find('#progress-div').hide(10000);
,
resetForm: false
);
return false;
);
/***********Error msg if file not valid***************/
$('input[type=file]').change(function ()
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(pdf|txt|jpg|png|doc|docx|xlx|xls|xlsx|jpg|ppt|pptx|tif|tiff|\n\
bmp|pcd|gif|bmp|zip|rar|odt|avi|ogg|m4a|mov|mp3|mp4|mpg|wav|wmv|stp|sldprt|sldasm|iges|igs|stl|x_t|step\n\
|stp|prt|asm|idw|iam|ipt|dxf|dwg|pdf|slddrw|dwf)$");
if (!(regex.test(val)))
$(this).val('');
alert('Please select correct file format');
);
/*********End*****************/
);
</script>
样式:
<style>
bodywidth:610px;
#uploadForm border-top:#F0F0F0 2px solid;background:#FAF8F8;padding:10px;
#uploadForm label margin:2px; font-size:1em; font-weight:bold;
.demoInputBoxpadding:5px; border:#F0F0F0 1px solid; border-radius:4px; background-color:#FFF;
#progress-bar background-color: #12CC1A;height:20px;color: #FFFFFF;width:0%;-webkit-transition: width .3s;-moz-transition: width .3s;transition: width .3s;
.btnSubmitbackground-color:#09f;border:0;padding:10px 40px;color:#FFF;border:#F0F0F0 1px solid; border-radius:4px;
#progress-div
border: 1px solid #0fa015;
border-radius: 4px;
margin: -35px 2px 7px 295px;
padding: 5px 0;
text-align: center;
width: 277px;
#targetLayerwidth:100%;text-align:center;
</style>
【讨论】:
这个插件(jQuery 形式)已经很老了。 ¿ 它仍然适用于当前的 jQuery 和浏览器吗?以上是关于Ajax上传文件怎样才能分块上传呢?的主要内容,如果未能解决你的问题,请参考以下文章