2013-03-14 472 views
110

我想在我的項目中實現AJAX文件上傳功能。我爲此使用jQuery;我的代碼使用AJAX提交數據。我也想實現一個文件上傳進度條。我怎樣才能做到這一點?有沒有什麼方法可以計算出已經上傳了多少,以便我可以計算上傳的百分比並創建一個進度條?帶jQuery的文件上傳進度條

+1

你看過jQuery插件或jQuery UI嗎? http://jqueryui.com/progressbar/ – 2013-03-14 13:14:14

+1

你見過[plugin homepage](http://www.malsup.com/jquery/form/#file-upload)上的例子嗎? – 2013-03-14 13:24:13

+2

查看jQuery插件[Uploadify](http://www.uploadify.com/)。 – Knelis 2013-03-14 13:30:07

回答

102

說明:此問題與jQuery form plugin有關。如果你正在尋找一個純粹的jQuery解決方案,start here。 所有瀏覽器都沒有整體的jQuery解決方案。所以你必須使用一個插件。我使用的是dropzone.js,它對舊版瀏覽器有一個簡單的回退功能。你喜歡哪個插件取決於你的需求。那裏有很多很好的比較,比如thisthisthis

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的進度......

+0

我使用了'uploadProgress'並使用了jquery-ui progressbar。謝謝 – 2013-03-14 17:09:37

+0

Hello Jam,我實現了ur代碼,但得到500內部服務器錯誤。 – 2013-04-20 07:57:38

+6

聽起來像你的PHP代碼有錯誤。你的file-echo2.php是怎麼樣的? – 2013-04-22 09:00:29

186

我只用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); 
    } 
}); 
+7

這更好,因爲它不需要jQuery.ajaxForm。只用jQuery核心庫就可以完美工作。 – 2014-05-06 07:30:31

+0

偉大的解決方案,謝謝 – waki 2014-05-30 08:59:34

+6

這是這裏唯一真正的答案。 (y) – 2015-02-06 17:57:11

7

如果您正在使用您的項目jQuery和不想從頭實現上傳機制,你可以使用https://github.com/blueimp/jQuery-File-Upload

他們有一個很好的api與多個文件選擇,拖動&拖放支持,進度條,驗證和預覽圖像,跨域支持,分塊和可恢復文件上傳。他們有多種服務器語言的示例腳本(節點,php,python和go)。

演示地址:https://blueimp.github.io/jQuery-File-Upload/

+0

我無法使用PHP配置該插件。你知不知道怎麼? – Avi 2017-02-21 23:16:49

15

我在我的項目中使用了以下內容。 你也可以試試。

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 id for sending upload form data. 
0

的JavaScript:

<script> 
/* jquery.form.min.js */ 
(function(e){"use strict";if(typeof define==="function"&&define.amd){define(["jquery"],e)}else{e(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){return}n=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.offsetY}else if(typeof e.fn.offset=="function"){var o=r.offset();s.clk_x=t.pageX-o.left;s.clk_y=t.pageY-o.top}else{s.clk_x=t.pageX-n.offsetLeft;s.clk_y=t.pageY-n.offsetTop}}setTimeout(function(){s.clk=s.clk_x=s.clk_y=null},100)}function s(){if(!e.fn.ajaxSubmit.debug){return}var 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 e}return 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 s}function 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 t}}u.data=null;var a=u.beforeSend;u.beforeSend=function(e,t){if(r.formData){t.data=r.formData}else{t.data=n}if(a){a.call(this,e,t)}};return e.ajax(u)}function A(t){function T(e){var t=null;try{if(e.contentWindow){t=e.contentWindow.document}}catch(n){s("cannot get iframe.contentWindow document: "+n)}if(t){return t}try{t=e.contentDocument?e.contentDocument:e.document}catch(n){s("cannot get iframe.contentDocument: "+n);t=e.document}return t}function k(){function f(){try{var 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=undefined}}var 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=[];try{if(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])}else{c.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",_)}else{v.addEventListener("load",_,false)}setTimeout(f,15);try{o.submit()}catch(m){var g=document.createElement("form").submit;g.apply(o)}}finally{o.setAttribute("action",n);o.setAttribute("enctype",u);if(t){o.setAttribute("target",t)}else{a.removeAttr("target")}e(c).remove()}}function _(t){if(m.aborted||M){return}A=T(v);if(!A){s("cannot access response document");t=x}if(t===S&&m){m.abort("timeout");E.reject(m,"timeout");return}else if(t==x&&m){m.abort("server abort");E.reject(m,"error","server abort");return}if(!A||A.location.href==l.iframeSrc){if(!b){return}}if(v.detachEvent){v.detachEvent("onload",_)}else{v.removeEventListener("load",_,false)}var n="success",r;try{if(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);return}}var 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.statusText}var 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.statusText}else if(a){var c=A.getElementsByTagName("pre")[0];var p=A.getElementsByTagName("body")[0];if(c){m.responseText=c.textContent?c.textContent:c.innerText}else if(p){m.responseText=p.textContent?p.textContent:p.innerText}}}else if(u=="xml"&&!m.responseXML&&m.responseText){m.responseXML=D(m.responseText)}try{L=H(m,u,l)}catch(g){n="parsererror";m.error=r=g||n}}catch(g){s("error caught: ",g);n="error";m.error=r=g||n}if(m.aborted){s("upload aborted");n=null}if(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.statusText}if(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()}else{d.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)}else{u.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)}else{p=y}}else{d=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;try{if(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 E}if(m.aborted){E.reject();return E}g=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_y}}}var 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]=N}if(l.forceSync){k()}else{setTimeout(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)}else{t=(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 E}if(!this.length){s("ajaxSubmit: skipping submit process - no element selected");return this}var i,o,u,a=this;if(typeof r=="function"){r={success:r}}else 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 this}if(r.beforeSerialize&&r.beforeSerialize(this,r)===false){s("ajaxSubmit: submit aborted via beforeSerialize callback");return this}var l=r.traditional;if(l===undefined){l=e.ajaxSettings.traditional}var 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 this}this.trigger("form-submit-validate",[p,this,r,f]);if(f.veto){s("ajaxSubmit: submit vetoed via form-submit-validate trigger");return this}var d=e.param(p,l);if(h){d=d?d+"&"+h:h}if(r.type.toUpperCase()=="GET"){r.url+=(r.url.indexOf("?")>=0?"&":"?")+d;r.data=null}else{r.data=d}var 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)})}else{N=A(p)}}else if((w||S)&&x){N=L(p)}else{N=e.ajax(r)}a.removeData("jqxhr").data("jqxhr",N);for(var C=0;C<c.length;C++){c[C]=null}this.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 this}s("terminating; zero elements found by selector"+(e.isReady?"":" (DOM not ready)"));return this}if(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 this}return 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 i}var 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 i}var 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){continue}if(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})}continue}h=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})}}else{i.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){return}var 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){continue}if(o.constructor==Array){e.merge(n,o)}else{n.push(o)}}return n};e.fieldValue=function(t,n){var r=t.name,i=t.type,s=t.tagName.toLowerCase();if(n===undefined){n=true}if(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 null}if(s=="select"){var o=t.selectedIndex;if(o<0){return null}var 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.value}if(f){return p}u.push(p)}}return u}return 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=false}else if(i=="select"){this.selectedIndex=-1}else if(r=="file"){if(/MSIE/.test(navigator.userAgent)){e(this).replaceWith(e(this).clone(true))}else{e(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=true}return this.each(function(){this.disabled=!e})};e.fn.selected=function(t){if(t===undefined){t=true}return this.each(function(){var n=this.type;if(n=="checkbox"||n=="radio"){this.checked=t}else 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> 
    body{width:610px;} 
    #uploadForm {border-top:#F0F0F0 2px solid;background:#FAF8F8;padding:10px;} 
    #uploadForm label {margin:2px; font-size:1em; font-weight:bold;} 
    .demoInputBox{padding: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;} 
    .btnSubmit{background-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; 
    } 

    #targetLayer{width:100%;text-align:center;} 
</style> 
+0

這個插件(jQuery表單)很舊。 ¿它仍然適用於當前的jQuery和瀏覽器? – 2018-01-19 15:54:34

+0

是的!它會工作。 – 2018-02-15 07:46:52

2

這裏是一個比較完整的jQuery尋找$ 1.11.x阿賈克斯()的用法:

<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> 
1

這解決了我的問題

$.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: posturlfile, 
    type: "POST", 
    data: JSON.stringify(fileuploaddata), 
    contentType: "application/json", 
    dataType: "json", 
    success: function(result) { 
    console.log(result); 
    } 
});