-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy patheasyuploader.min.js
1 lines (1 loc) · 9.82 KB
/
easyuploader.min.js
1
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).EasyUploader=t()}(this,function(){"use strict";var e={el:"",name:"file",id:"",accept:"",file:"#file",method:"post",url:"",resType:"json",autoUpload:!0,maxFileSize:"2M",tipClass:"",allowDrag:!1,clip:!1,fixOrientation:!0,allowFileExt:[],language:"cn",compress:!0,resize:{maxWidth:800,maxHeight:800},compressQuality:.92,tipDurationTime:3},t={en:{noFile:"Please choose the file first.",fileTooLarge:"The file is too Large. The maxFileSize is {0}.",fileExtNotAllow:"The file extension is not allowed to upload. Please upload the {0} file."},cn:{noFile:"请先选择文件",fileTooLarge:"文件太大,最大允许为{0}",fileExtNotAllow:"文件扩展名不允许上传,请上传{0}格式的文件"}},i=function(){};i.extend=function(e,t){for(var i in t)if(i in e){if(e[i].constructor===t[i].constructor)if(e[i].constructor===Object){var o=e[i],n=t[i];for(var a in n)o[a]=n[a];e[i]=o}else e[i]=t[i]}else e[i]=t[i];return e},i.base64ToArrayBuffer=function(e){e=e.replace(/^data:([^;]+);base64,/gim,"");for(var t=atob(e),i=t.length,o=new ArrayBuffer(i),n=new Uint8Array(o),a=0;a<i;a++)n[a]=t.charCodeAt(a);return o},i.getOrientation=function(e){var t,i,o,n,a,s,r,l,p,f,c=new DataView(e),h=c.byteLength;if(255===c.getUint8(0)&&216===c.getUint8(1))for(p=2;p<h;){if(255===c.getUint8(p)&&225===c.getUint8(p+1)){r=p;break}p++}if(r&&(i=r+4,o=r+10,"Exif"===this.getStringFromCharCode(c,i,4)&&((a=18761===(s=c.getUint16(o)))||19789===s)&&42===c.getUint16(o+2,a)&&(n=c.getUint32(o+4,a))>=8&&(l=o+n)),l)for(h=c.getUint16(l,a),f=0;f<h;f++)if(p=l+12*f+2,274===c.getUint16(p,a)){p+=8,t=c.getUint16(p,a),navigator.userAgent.indexOf("Safari")>-1&&c.setUint16(p,1,a);break}return t},i.getStringFromCharCode=function(e,t,i){var o,n="";for(o=t,i+=t;o<i;o++)n+=String.fromCharCode(e.getUint8(o));return n},i.getNonce=function(e){e||(e=16);for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890",i="",o=0;o<e;o++)i+=t.charAt(Math.floor(Math.random()*t.length));return i},i.replacePlaceholders=function(e,t){e||(e=""),t||(t=[]);for(var i=0;i<t.length;i++)e=e.replace(new RegExp("\\{"+i+"\\}","g"),t[i]);return e},i.handleRes=function(e,t){return"json"===t?JSON.parse(e):e},i.evil=function(e){return new Function("return "+e)()};HTMLCanvasElement.prototype.toBlob||Object.defineProperty(HTMLCanvasElement.prototype,"toBlob",{value:function(e,t,i){for(var o=atob(this.toDataURL(t,i).split(",")[1]),n=o.length,a=new Uint8Array(n),s=0;s<n;s++)a[s]=o.charCodeAt(s);e(new Blob([a],{type:t||"image/png"}))}});var o=function t(o){if(void 0===o&&(o={}),!(this instanceof t))return new t(o);this.classPrefix="easyuploader".toLowerCase(),this.version="0.0.10",this.fileObj="",this.elObj="",this.fileType="",this.fileName="",this.fileSize="",this.fileExt="",this.fileObjClickStatus=!0,this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),this.formData=new FormData,this.tips={},this.options=i.extend(JSON.parse(JSON.stringify(e)),o),this.init()};return o.prototype.init=function(){var e=JSON.parse(JSON.stringify(t));this.tips=e.hasOwnProperty(this.options.language)?e[this.options.language]:e.cn,this.options.el?(this.elObj=document.querySelector(this.options.el),this.createInput(),this.bindElToInput(),this.options.allowDrag&&this.listenDrag(this.elObj)):(this.fileObj=document.querySelector(this.options.file),this.options.allowDrag&&this.listenDrag(this.fileObj)),this.listenFileObjClick(),this.listenFileObjChange()},o.prototype.createInput=function(){this.options.id||(this.options.id=this.classPrefix+"_"+i.getNonce());var e=document.createElement("input");e.type="file",e.name=this.options.name,e.id=this.options.id,e.accept=this.options.accept,e.setAttribute("style","display: none !important;"),this.elObj.parentNode.insertBefore(e,this.elObj.nextElementSibling),this.fileObj=document.querySelector("#"+this.options.id)},o.prototype.bindElToInput=function(){var e=this;e.elObj.addEventListener("click",function(t){t.preventDefault(),e.fileObj.click()})},o.prototype.enableFileObjClick=function(){this.fileObjClickStatus=!0},o.prototype.disableFileObjClick=function(){this.fileObjClickStatus=!1},o.prototype.listenFileObjClick=function(){var e=this;e.fileObj.addEventListener("click",function(t){e.fileObjClickStatus||t.preventDefault()})},o.prototype.listenFileObjChange=function(){var e=this;e.fileObj.addEventListener("change",function(){e.fileIsChosen()})},o.prototype.listenDrag=function(e){var t=this;e.addEventListener("drop",function(e){e.preventDefault(),t.options.onDrop&&t.options.onDrop(e),t.fileObj.files=e.dataTransfer.files,t.fileIsChosen()}),e.addEventListener("dragover",function(e){e.preventDefault(),t.options.onDragOver&&t.options.onDragOver(e)}),e.addEventListener("dragenter",function(e){e.preventDefault(),t.options.onDragEnter&&t.options.onDragEnter(e)}),e.addEventListener("dragleave",function(e){e.preventDefault(),t.options.onDragLeave&&t.options.onDragLeave(e)})},o.prototype.fileIsChosen=function(){this.fileType=this.fileObj.files[0].type,this.fileName=this.fileObj.files[0].name,this.fileExt=this.fileName.split(".").pop().toLowerCase(),this.fileSize=this.fileObj.files[0].size,this.checkFile()&&(this.needCanvas()?this.drawAndRenderCanvas():this.options.autoUpload&&this.uploadFile(this.fileObj.files[0]))},o.prototype.drawAndRenderCanvas=function(){var e=this,t=new FileReader,o=new Image,n=new ArrayBuffer,a=1,s="",r="";t.readAsDataURL(e.fileObj.files[0]),t.onload=function(e){n=i.base64ToArrayBuffer(e.target.result),a=i.getOrientation(n),o.src=e.target.result},o.onload=function(){if(e.options.compress?o.width>e.options.resize.maxWidth||o.height>e.options.resize.maxHeight?o.width>o.height?(s=e.options.resize.maxWidth,r=o.height/o.width*e.options.resize.maxWidth):(s=o.width/o.height*e.options.resize.maxHeight,r=e.options.resize.maxHeight):(s=o.width,r=o.height):(s=o.width,r=o.height,e.options.compressQuality=1),e.options.fixOrientation)switch(a){case 3:e.canvas.width=s,e.canvas.height=r,e.context.rotate(180*Math.PI/180),e.context.drawImage(o,-s,-r,s,r);break;case 6:e.canvas.width=r,e.canvas.height=s,e.context.rotate(90*Math.PI/180),e.context.drawImage(o,0,-r,s,r);break;case 8:e.canvas.width=r,e.canvas.height=s,e.context.rotate(270*Math.PI/180),e.context.drawImage(o,-s,0,s,r);break;case 1:default:e.canvas.width=s,e.canvas.height=r,e.context.drawImage(o,0,0,s,r)}else e.canvas.width=s,e.canvas.height=r,e.context.drawImage(o,0,0,s,r);e.canvas.setAttribute("style","display: none !important;"),document.querySelector("body").appendChild(e.canvas),e.options.autoUpload&&e.uploadCanvas()}},o.prototype.upload=function(){this.fileType.indexOf("image/")>=0&&this.options.compress?this.uploadCanvas():this.uploadFile(this.fileObj.files[0])},o.prototype.uploadCanvas=function(){var e=this;e.fileObj.files[0]?e.canvas.toBlob(function(t){e.uploadFile(t)},e.fileType,e.options.compressQuality):e.renderTipDom(this.tips.noFile)},o.prototype.uploadFile=function(e){var t=this,o=this;if(o.fileObj.files[0]){o.formData.has(o.options.name)&&o.formData.delete(o.options.name),o.formData.append(o.options.name,e,o.fileName);var n=new XMLHttpRequest;n.open(o.options.method,o.options.url,!0),n.upload.addEventListener("progress",function(e){o.options.onUploadProgress&&o.options.onUploadProgress(e)}),n.upload.addEventListener("loadstart",function(e){o.options.onUploadStart&&o.options.onUploadStart(e)}),n.onreadystatechange=function(){4===n.readyState&&(n.status>=200&&n.status<300||304===n.status?o.options.onUploadComplete&&o.options.onUploadComplete(i.handleRes(n.responseText,t.options.resType.toLowerCase())):o.options.onUploadError&&o.options.onUploadError(n.status),o.needCanvas()&&o.canvas.remove(),o.fileObj.value="")},n.send(o.formData)}else o.renderTipDom(this.tips.noFile)},o.prototype.renderTipDom=function(t){var i=document.getElementById(this.classPrefix+"_tipdom");i&&i.remove();var o=document.createElement("div");o.id=this.classPrefix+"_tipdom",o.innerHTML=t,this.options.tipClass?o.className=this.options.tipClass:o.setAttribute("style","max-width: 100%;padding: 16px 20px;font-size: 14px;color: #fff;box-sizing: border-box;border-radius: 2px;filter: Alpha(opacity=80);opacity: 0.8;-moz-opacity: 0.8;user-select: none;position: fixed;top: 50%;left: 50%;z-index: 100000;transform: translate(calc(-50% + 0.5px), calc(-50% + 0.5px));-webkit-transform: translate(calc(-50% + 0.5px), calc(-50% + 0.5px));text-align: center;background: #000;word-wrap: break-word;word-break: break-all;"),document.querySelector("body").appendChild(o);var n=e.tipDurationTime;"number"==typeof this.options.tipDurationTime&&this.options.tipDurationTime>0&&(n=this.options.tipDurationTime),setTimeout(function(){var e=o.style.opacity;if(e>0){(e=(e-.2).toFixed(1))<0&&(e=0);var t=setInterval(function(){o.style.opacity=e,o.style.filter="Alpha((opacity = "+100*e+"))",e<=0?(o.remove(),clearInterval(t)):(e=(e-.1).toFixed(1))<0&&(e=0)},10)}else o.remove()},1e3*n)},o.prototype.checkFile=function(){var e=this.options.maxFileSize,t=0,o="";return e.indexOf("B")>0&&(e=e.replace(/B/g,""),o="B"),e.indexOf("K")>0?(t=i.evil(e.replace(/K/g,"")),e=1024*t,o="K"+o):e.indexOf("M")>0?(t=i.evil(e.replace(/M/g,"")),e=1024*t*1024,o="M"+o):e.indexOf("G")>0?(t=i.evil(e.replace(/G/g,"")),e=1024*t*1024*1024,o="G"+o):e.indexOf("T")>0?(t=i.evil(e.replace(/T/g,"")),e=1024*t*1024*1024*1024,o="T"+o):e.indexOf("P")>0?(t=i.evil(e.replace(/P/g,"")),e=1024*t*1024*1024*1024*1024,o="P"+o):(e=t=i.evil(e),o="B"),this.fileSize>e?(this.renderTipDom(i.replacePlaceholders(this.tips.fileTooLarge,[t+o])),this.fileObj.value="",!1):!(this.options.allowFileExt.length>0&&-1===this.options.allowFileExt.indexOf(this.fileExt))||(this.renderTipDom(i.replacePlaceholders(this.tips.fileExtNotAllow,[this.options.allowFileExt.join(",")])),this.fileObj.value="",!1)},o.prototype.needCanvas=function(){return!!(this.fileType.indexOf("image/")>=0&&(this.options.compress||this.options.clip))},o});