ais-uploader
Version:
Simple uploader library for Angular 2+
2 lines • 19 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("rxjs/operators"),require("@angular/core"),require("rxjs"),require("@angular/common"),require("@angular/common/http")):"function"==typeof define&&define.amd?define("ais-uploader",["exports","rxjs/operators","@angular/core","rxjs","@angular/common","@angular/common/http"],t):t(e["ais-uploader"]={},e.rxjs.operators,e.ng.core,e.rxjs,e.ng.common,e.ng.common.http)}(this,function(e,p,o,i,s,n){"use strict";function t(t,s,a,u){return new(a||(a=Promise))(function(e,n){function r(e){try{i(u.next(e))}catch(t){n(t)}}function o(e){try{i(u["throw"](e))}catch(t){n(t)}}function i(t){t.done?e(t.value):new a(function(e){e(t.value)}).then(r,o)}i((u=u.apply(t,s||[])).next())})}function h(r,o){var i,s,a,e,u={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return e={next:t(0),"throw":t(1),"return":t(2)},"function"==typeof Symbol&&(e[Symbol.iterator]=function(){return this}),e;function t(t){return function(e){return function n(e){if(i)throw new TypeError("Generator is already executing.");for(;u;)try{if(i=1,s&&(a=2&e[0]?s["return"]:e[0]?s["throw"]||((a=s["return"])&&a.call(s),0):s.next)&&!(a=a.call(s,e[1])).done)return a;switch(s=0,a&&(e=[2&e[0],a.value]),e[0]){case 0:case 1:a=e;break;case 4:return u.label++,{value:e[1],done:!1};case 5:u.label++,s=e[1],e=[0];continue;case 7:e=u.ops.pop(),u.trys.pop();continue;default:if(!(a=0<(a=u.trys).length&&a[a.length-1])&&(6===e[0]||2===e[0])){u=0;continue}if(3===e[0]&&(!a||e[1]>a[0]&&e[1]<a[3])){u.label=e[1];break}if(6===e[0]&&u.label<a[1]){u.label=a[1],a=e;break}if(a&&u.label<a[2]){u.label=a[2],u.ops.push(e);break}a[2]&&u.ops.pop(),u.trys.pop();continue}e=o.call(r,u)}catch(t){e=[6,t],s=0}finally{i=a=0}if(5&e[0])throw e[1];return{value:e[0]?e[1]:void 0,done:!0}}([t,e])}}}function d(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}function g(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),s=[];try{for(;(void 0===t||0<t--)&&!(r=i.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(n=i["return"])&&n.call(i)}finally{if(o)throw o.error}}return s}var r,a=function(){function e(e){this.http=e,this._uploadingProgress$=new i.BehaviorSubject(0)}return Object.defineProperty(e.prototype,"uploadingProgress",{get:function(){return this._uploadingProgress$.asObservable()},enumerable:!0,configurable:!0}),e.prototype.upload=function(e,t){var n=this;if(!e)return null;this._uploadingProgress$.next(0);var r=new FormData;return r.append("file",e),this.http.post(""+t.apiUrl,r,{headers:t.headers,responseType:t.responseType,reportProgress:!0,observe:"events"}).pipe(p.map(function(e){return n.getEventMessage(e)}),p.last())},e.prototype.uploadMultiple=function(e,t){var n,r,o=this;if(!e||!e.length)return null;var i=new FormData;try{for(var s=d(e),a=s.next();!a.done;a=s.next()){var u=a.value;i.append("file",u)}}catch(l){n={error:l}}finally{try{a&&!a.done&&(r=s["return"])&&r.call(s)}finally{if(n)throw n.error}}return this.http.post(""+t.apiUrl,i,{headers:t.headers,responseType:t.responseType,reportProgress:!0,observe:"events"}).pipe(p.map(function(e){return o.getEventMessage(e)}),p.last())},e.prototype.getEventMessage=function(e){if(e.type)switch(e.type){case n.HttpEventType.UploadProgress:var t=Math.round(100*e.loaded/e.total);return void this.showProgress(t);case n.HttpEventType.Response:return this.resetProgress(),e.body;default:return 0}},e.prototype.showProgress=function(e){this._uploadingProgress$.next(e)},e.prototype.resetProgress=function(){},e.decorators=[{type:o.Injectable}],e.ctorParameters=function(){return[{type:n.HttpClient}]},e}(),u={DOCX:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",DOC:"application/msword",PDF:"application/pdf",XLSX:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",XLS:"application/vnd.ms-excel",PPTX:"application/vnd.openxmlformats-officedocument.presentationml.presentation",PPT:"application/vnd.ms-powerpoint",TXT:"text/plain",MP4:"video/mp4",AVI:"video/avi",MPEG:"video/mpeg",FLV:"video/x-flv",WEBM:"video/webm",OGG:"video/ogg",MOV:"video/quicktime",MSCSV:"application/vnd.ms-excel",CSV:"text/csv",JPEG:"image/jpeg",JPG:"image/jpeg",PNG:"image/png",WEBP:"image/webp",WBMP:"image/vnd.wap.wbmp",SVG:"image/svg+xml",TIFF:"image/tiff",GIF:"image/gif",MP3:"audio/mpeg",WAV:"audio/wav",XWAV:"audio/x-wav"},l=function(){function e(){this.DocumentFileType=u}return e.prototype.transform=function(e,t){var n,r;if(void 0===t&&(t=!1),e){var o=[];try{for(var i=d(e),s=i.next();!s.done;s=i.next()){var a=s.value;for(var u in this.DocumentFileType)if(a===this.DocumentFileType[u]){if(o.includes("."+u.toLowerCase())||o.includes(u.toLowerCase()))continue;o.push(t?"."+u.toLowerCase():u.toLowerCase())}}}catch(l){n={error:l}}finally{try{s&&!s.done&&(r=i["return"])&&r.call(i)}finally{if(n)throw n.error}}return o.join(", ")}},e.decorators=[{type:o.Injectable,args:[{providedIn:"root"}]},{type:o.Pipe,args:[{name:"uploaderTypes"}]}],e.ngInjectableDef=o.defineInjectable({factory:function(){return new e},token:e,providedIn:"root"}),e}(),c=function(){function e(e,t,n){function r(e,t){t=t||{bubbles:!1,cancelable:!1,detail:undefined};var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),n}this.uploderService=t,this.uploaderEnum=n,this.onChange=new o.EventEmitter,this.onProgress=new o.EventEmitter,this.onError=new o.EventEmitter,this._allowedExtensions=[],s.isPlatformServer(e)||"function"==typeof window.MouseEvent||(r.prototype=window.Event.prototype,window.CustomEvent=r)}return e.prototype.ngOnInit=function(){this._generateAllowedExtensions()},e.prototype.ngOnDestroy=function(){this._progressSub$&&this._progressSub$.unsubscribe(),this._uploaderSub$&&this._uploaderSub$.unsubscribe()},Object.defineProperty(e.prototype,"fileName",{get:function(){return this.config.isMultiple?this.filesNames:this._file?this._file.name:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"filesNames",{get:function(){return this._files&&this._files.length?this._files.map(function(e){return e.name}):undefined},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tooltipMessage",{get:function(){return this.config.supportedFormats.length?"Supported formats are "+(this.uploaderEnum.transform(this.config.supportedFormats)||"All formats")+". Max. size is "+(this.config.maxSize?this.config.maxSize:"unlimited")+" Mb":"Max. size is "+(this.config.maxSize?this.config.maxSize:"unlimited")+" Mb"},enumerable:!0,configurable:!0}),e.prototype.select=function(){var e;e="function"==typeof window.MouseEvent?new MouseEvent("click",{}):new CustomEvent("click"),this.fileSelector.nativeElement.dispatchEvent(e)},e.prototype["delete"]=function(e){this._files.splice(e,1)},e.prototype.clear=function(e){void 0===e&&(e=!0),this._file=undefined,this._files=undefined,this.fileSelector.nativeElement.value="",e&&this.onChange.emit("")},e.prototype.loadFile=function(f){return t(this,void 0,void 0,function(){var t,r,o,i,s,a,u,l,p,c;return h(this,function(e){switch(e.label){case 0:if(!this.config.isMultiple)return[3,9];o=f.target.files,e.label=1;case 1:e.trys.push([1,6,7,8]),i=d(o),s=i.next(),e.label=2;case 2:return s.done?[3,5]:(a=s.value,[4,this.validate(a)]);case 3:if(!e.sent())return[2];e.label=4;case 4:return s=i.next(),[3,2];case 5:return[3,8];case 6:return u=e.sent(),t={error:u},[3,8];case 7:try{s&&!s.done&&(r=i["return"])&&r.call(i)}finally{if(t)throw t.error}return[7];case 8:return this._files=function n(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(g(arguments[t]));return e}(o),[3,11];case 9:return(l=f.target.files[0])?[4,this.validate(l)]:[2];case 10:if(!e.sent())return[2];this._file=l,e.label=11;case 11:if(!this.config.isAutoupload)return[3,16];e.label=12;case 12:return e.trys.push([12,14,,15]),[4,this.upload()];case 13:return p=e.sent(),this.onChange.emit(p),[3,15];case 14:return c=e.sent(),this.onError.emit(c),[3,15];case 15:return[2];case 16:return this.config.isPreviewDisabled?this.onChange.emit(this._file.name):this._makePreview(),[2]}})})},e.prototype.upload=function(){var n=this;return this._progressSub$&&this._progressSub$.unsubscribe(),this._onLoaderSub(),this.config.isMultiple?new Promise(function(t){n._uploaderSub$=n.uploderService.uploadMultiple(n._files,n.config).subscribe(function(e){n.onProgress.emit(0),n.uploadingProgress=0,t(e)},function(e){n.onError.emit("Uploading error"),n.preventUploading(),t(undefined)})}):new Promise(function(t){n._uploaderSub$=n.uploderService.upload(n._file,n.config).subscribe(function(e){n.onProgress.emit(0),n.uploadingProgress=0,t(e)},function(e){n.onError.emit("Uploading error"),n.preventUploading(),t(undefined)})})},e.prototype.preventUploading=function(){this.uploadingProgress&&(this._progressSub$&&this._progressSub$.unsubscribe(),this._uploaderSub$&&this._uploaderSub$.unsubscribe(),this.onProgress.emit(0),this.uploadingProgress=0,this.clear())},e.prototype.validate=function(r){return t(this,void 0,void 0,function(){var t,n;return h(this,function(e){switch(e.label){case 0:if(!r||!this.config)return this.throwError("Uploader error"),[2,!1];if(this.config.maxSize&&r.size/1024/1024>this.config.maxSize)return this.throwError("File size should be no more than "+this.config.maxSize+"Mb"),[2,!1];if(this.config.supportedFormats.length&&r.type&&!this.config.supportedFormats.includes(r.type))return this.throwError("Unsupported file format"),[2,!1];if(this.config.supportedFormats.length&&!r.type&&!this._validateFormat(r.name))return this.throwError("Unsupported file format"),[2,!1];if(!this.config.imageResolution)return[3,5];if(t=this.config.imageResolution.split("x"),n=void 0,!t||!t.length||2!==t.length)return this.throwError("Unsupported resolution format"),[2,!1];if(!(t=t.map(function(e){return Math.ceil(Number(e))}).filter(function(e){return!!e}))||!t.length||2!==t.length)return this.throwError("Unsupported resolution format"),[2,!1];e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this._addImageProcess(r)];case 2:return n=e.sent(),[3,4];case 3:return e.sent(),console.warn("Resolution property allows only for Images - Error Skipped"),[2,!0];case 4:if(n.width!==t[0]||n.height!==t[1])return this.throwError("Unsupported resolution format! Correct resolution is "+this.config.imageResolution),[2,!1];e.label=5;case 5:return[2,!0]}})})},e.prototype._addImageProcess=function(i){return t(this,void 0,void 0,function(){return h(this,function(e){return[2,new Promise(function(e,t){var n=window.URL||window.webkitURL,r=new Image,o=n.createObjectURL(i);r.onload=function(){return n.revokeObjectURL(o),e({height:r.height,width:r.width})},r.onerror=t,r.src=o})]})})},e.prototype._onLoaderSub=function(){var t=this;this._progressSub$=this.uploderService.uploadingProgress.subscribe(function(e){t.onProgress.emit(e),t.uploadingProgress=e})},e.prototype._makePreview=function(){var t=this;if(this.config.isMultiple)for(var n=[],e=function(t){var e=new FileReader;e.onload=function(e){n[t]=e.target.result},e.readAsDataURL(r._files[t]),t==r._files.length-1&&r.onChange.emit(n)},r=this,o=0;o<this._files.length;o++)e(o);else{var i=new FileReader;i.onload=function(e){t.onChange.emit(e.target.result)},i.readAsDataURL(this._file)}},e.prototype._validateFormat=function(e){if(!this.config.supportedFormats.length)return!0;var t=e.split(".").pop().toLowerCase();return this._allowedExtensions.some(function(e){return e===t})},e.prototype.throwError=function(e){this.onError.emit(e),this.fileSelector.nativeElement.value=""},e.prototype._generateAllowedExtensions=function(){var e,t;if(this.config&&this.config.supportedFormats)try{for(var n=d(this.config.supportedFormats),r=n.next();!r.done;r=n.next()){switch(r.value){case u.DOC:this._allowedExtensions.push("doc");break;case u.DOCX:this._allowedExtensions.push("docx");break;case u.XLSX:this._allowedExtensions.push("xlsx");break;case u.XLS:this._allowedExtensions.push("xls");break;case u.PDF:this._allowedExtensions.push("pdf");break;case u.TXT:this._allowedExtensions.push("txt");break;case u.PPTX:this._allowedExtensions.push("pptx");break;case u.PPT:this._allowedExtensions.push("ppt");break;case u.AVI:this._allowedExtensions.push("avi");break;case u.FLV:this._allowedExtensions.push("flv");break;case u.MP4:this._allowedExtensions.push("mp4");break;case u.MPEG:this._allowedExtensions.push("mpeg");break;case u.OGG:this._allowedExtensions.push("ogg");break;case u.WEBM:this._allowedExtensions.push("webm");break;case u.JPEG:this._allowedExtensions.push("jpeg");break;case u.JPG:this._allowedExtensions.push("jpg");break;case u.PNG:this._allowedExtensions.push("png");break;case u.TIFF:this._allowedExtensions.push("tiff");break;case u.WBMP:this._allowedExtensions.push("wbmp");break;case u.WEBP:this._allowedExtensions.push("webp");break;case u.SVG:this._allowedExtensions.push("svg");break;case u.GIF:this._allowedExtensions.push("gif");break;case u.CSV:case u.MSCSV:this._allowedExtensions.push("csv");break;case u.MOV:this._allowedExtensions.push("mov");break;case u.MP3:this._allowedExtensions.push("mp3");break;case u.WAV:case u.XWAV:this._allowedExtensions.push("wav")}}}catch(o){e={error:o}}finally{try{r&&!r.done&&(t=n["return"])&&t.call(n)}finally{if(e)throw e.error}}},e.decorators=[{type:o.Component,args:[{selector:"ais-uploader",template:'<input id="uploader_lib" #fileSelector type="file" [accept]="config?.supportedFormats | uploaderTypes:true"\r\n (change)="loadFile($event)">\r\n',encapsulation:o.ViewEncapsulation.None,styles:["#uploader_lib{display:none}@keyframes blink{0%,100%{box-shadow:0 2px 2px rgba(0,0,0,.24),0 0 2px rgba(0,0,0,.12)}50%{box-shadow:none}}@-webkit-keyframes blink{0%,100%{box-shadow:0 2px 2px rgba(0,0,0,.24),0 0 2px rgba(0,0,0,.12)}50%{box-shadow:0 0 0}}.blink{-webkit-animation:3s linear infinite blink;animation:3s linear infinite blink}"]}]}],e.ctorParameters=function(){return[{type:String,decorators:[{type:o.Inject,args:[o.PLATFORM_ID]}]},{type:a},{type:l}]},e.propDecorators={onChange:[{type:o.Output}],onProgress:[{type:o.Output}],onError:[{type:o.Output}],fileSelector:[{type:o.ViewChild,args:["fileSelector"]}]},e}(),f=function(){function e(e,t,n,r){this.factory=e,this.ref=t,this.viewContainerRef=n,this.renderer=r,this.onChange=new o.EventEmitter,this.onProgress=new o.EventEmitter,this.onError=new o.EventEmitter,this._sub$=new i.Subscription}return Object.defineProperty(e.prototype,"config",{get:function(){return this._config},set:function(e){e!==this._config&&(this._config=e)},enumerable:!0,configurable:!0}),e.prototype.ngOnInit=function(){this.config.apiUrl&&this.config.supportedFormats?this._setBtnContainer():this.onError.emit("Incorrect config!")},e.prototype.ngOnDestroy=function(){this.viewContainerRef.clear(),this._clickFn&&this._clickFn()},Object.defineProperty(e.prototype,"instance",{get:function(){if(this._btnContainer)return this._btnContainer.instance},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"fileName",{get:function(){if(this.instance)return this.instance.fileName},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tooltipMessage",{get:function(){if(this.instance)return this.instance.tooltipMessage},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"progress",{get:function(){if(this.instance)return this.instance.uploadingProgress},enumerable:!0,configurable:!0}),e.prototype["delete"]=function(e){this.instance&&this.instance["delete"](e)},e.prototype.clear=function(e){void 0===e&&(e=!0),this.instance&&this.instance.clear(e)},e.prototype.preventUploading=function(){this.instance&&this.instance.preventUploading()},e.prototype.upload=function(){if(this.instance)return this.instance.upload()},e.prototype.onDragOver=function(e){var t=this._getTransfer(e);this._haveFiles(t.types)&&(t.dropEffect="copy",this._preventAndStop(e))},e.prototype.onDragLeave=function(e){this.element&&e.currentTarget===this.element[0]||this._preventAndStop(e)},e.prototype.onDrop=function(e){if(this.config.isDropAllowed){var t=this._getTransfer(e);t&&(this._preventAndStop(e),this.instance.loadFile({target:{files:t.files}}))}},e.prototype._getTransfer=function(e){return e.dataTransfer?e.dataTransfer:e.originalEvent.dataTransfer},e.prototype._preventAndStop=function(e){e.preventDefault(),e.stopPropagation()},e.prototype._haveFiles=function(e){return!!e&&(e.indexOf?-1!==e.indexOf("Files"):!!e.contains&&e.contains("Files"))},e.prototype._setBtnContainer=function(){var t=this,e=this.factory.resolveComponentFactory(c);this._btnContainer=this.viewContainerRef.createComponent(e),this._btnContainer.instance.config=this.config,this._clickFn=this.renderer.listen(this.ref.nativeElement,"click",function(e){return t._handleClick(e)}),this._sub$.add(this._btnContainer.instance.onChange.subscribe(function(e){return t.onChange.emit(e)})),this._sub$.add(this._btnContainer.instance.onError.subscribe(function(e){return t.onError.emit(e)})),this._sub$.add(this._btnContainer.instance.onProgress.subscribe(function(e){return t.onProgress.emit(e)}))},e.prototype._handleClick=function(e){var t=Object.values(e.target.attributes).map(function(e){return e.name});t.find(function(e){return"clear"==e})&&this.fileName&&!this.instance.uploadingProgress?this.clear():t.find(function(e){return"stop"==e})&&this.fileName&&this.instance.uploadingProgress?this.preventUploading():this._btnContainer.instance.select()},e.decorators=[{type:o.Directive,args:[{selector:"[uploader]",exportAs:"uploader"}]}],e.ctorParameters=function(){return[{type:o.ComponentFactoryResolver},{type:o.ElementRef},{type:o.ViewContainerRef},{type:o.Renderer2}]},e.propDecorators={config:[{type:o.Input,args:["uploader"]}],onChange:[{type:o.Output}],onProgress:[{type:o.Output}],onError:[{type:o.Output}],onDragOver:[{type:o.HostListener,args:["dragover",["$event"]]}],onDragLeave:[{type:o.HostListener,args:["dragleave",["$event"]]}],onDrop:[{type:o.HostListener,args:["drop",["$event"]]}]},e}(),m=function(){function e(){}return e.forRoot=function(){return{ngModule:e,providers:[]}},e.decorators=[{type:o.NgModule,args:[{declarations:[c,f,l],imports:[s.CommonModule,n.HttpClientModule],exports:[c,f],providers:[a],entryComponents:[c]}]}],e}(),b=function v(e,t,n,r,o,i,s){void 0===t&&(t=[]),void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=0),void 0===i&&(i=!1),void 0===s&&(s=!1),this.apiUrl=e,this.supportedFormats=t,this.isPreviewDisabled=s,this.maxSize=o,this.isAutoupload=i,this.isMultiple=n,this.isDropAllowed=r};(r=e.UploaderResponseType||(e.UploaderResponseType={})).JSON="json",r.BUFFER="arraybuffer",r.BLOB="blob",r.TEXT="text",e.AisUploaderService=a,e.AisUploaderComponent=c,e.AisUploaderModule=m,e.UploaderConfig=b,e.DocumentFileType=u,e.UploaderDirective=f,e.ɵa=l,Object.defineProperty(e,"__esModule",{value:!0})});
//# sourceMappingURL=ais-uploader.umd.min.js.map