uploadjs.js
2.82 KB
define([],function(){var e={};return e.uploadFile=function(e){function o(){var e='<div id="process-bar" style="width:100%;position: absolute;top:0;bottom: 0;z-index: 222;display: flex;justify-content: center;flex-direction: column;"><div style="width: 70%;margin: 0 auto;height:1.5rem;background: #dcdcdc;"><div style="height:1.5rem;width:0%;line-height: 1.5rem;background:#4ae637;text-align:center" id="pro-bar">0%</div></div></div>';if(""!=t.processAppendTo){var o=document.querySelector(t.processAppendTo);if(!o)return"";var r=o.querySelector("#process-bar");o&&r&&o.removeChild(r),o.insertAdjacentHTML("beforeend",e)}}var t={selector:e.selector||"",url:e.url||"",processAppendTo:e.processAppendTo||"",timeout:e.timeout||6e3,beforeSend:function(e,o){},success:function(o,t){e.success&&e.success(o,t)},complete:function(o,t){e.complete&&e.complete(o,t)},process:function(e){},ontimeout:function(e){},error:function(o,t){e.error&&e.error(o,t)}};t.beforeSend=function(t,r){e.beforeSend?e.beforeSend(t,r):o()},t.process=function(o){if(e.process)e.process(o);else if(""!=t.processAppendTo){var r=document.querySelector(t.processAppendTo);if(!r)return"";var n=r.querySelector("#pro-bar");if(n){var s=100*o.loaded/o.total,i=Math.floor(s)+"%";n.style.width=i,n.innerHTML=i}}},t.ontimeout=function(o){e.ontimeout?e.ontimeout(o):console.log("time out")};var r=document.querySelector(t.selector).files[0],n="",s=r.size/1024;t.uploadPost=function(e,o){var r=new FormData,n=new XMLHttpRequest;n.timeout=t.timeout,n.onload=function(e){var o=JSON.parse(""==this.response||null==this.response?"[]":this.response);t.success(o,e)},n.onloadend=function(e){if(""!=t.processAppendTo){var o=document.querySelector(t.processAppendTo);if(o){var r=o.querySelector("#process-bar");o&&o.removeChild(r)}}var n=JSON.parse(""==this.response||null==this.response?"[]":this.response);t.complete(n,e)},n.onerror=function(e){var o=JSON.parse(""==this.response||null==this.response?"[]":this.response);t.error(o,e)},n.ontimeout=function(e){console.log("request timeout"),t.ontimeout(e)},n.addEventListener("loadstart",function(e){t.beforeSend(e)}),n.open("post",t.url,!0),n.upload.onprogress=function(e){e.lengthComputable&&t.process(e)},r.append("uploadType",o),r.append("file",e),n.send(r)},t.compressAndUpload=function(e,r){var n=new FileReader,s=new Image,i=e,c=document.createElement("canvas"),a=c.getContext("2d");if(void 0!=i&&""!=i){if(0!=i.type.indexOf("image"))return!1;n.readAsDataURL(i),n.onload=function(e){s.src=e.target.result},o(),s.onload=function(){var e=this,o=((new Date).getTime(),e.width),n=e.height,s=1024,i=1024,u=o,d=n;(o>s||n>i)&&(o/n>s/i?(u=s,d=Math.round(s*(n/o))):(d=i,u=Math.round(i*(o/n)))),c.width=u,c.height=d,a.clearRect(0,0,u,d),a.drawImage(e,0,0,u,d);var p=c.toDataURL("image/jpeg",.7);t.uploadPost(p,r)}}},s<=1024?(n="file",t.uploadPost(r,n)):(n="base64",t.compressAndUpload(r,n))},e});