forked from jackrabbitsgroup/angular-image-upload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
image-upload.min.js
1 lines (1 loc) · 17 KB
/
image-upload.min.js
1
"use strict";angular.module("jackrabbitsgroup.angular-image-upload",[]).directive("jrgImageUpload",["jrgImageUploadData","$timeout",function(jrgImageUploadData,$timeout){return{restrict:"A",scope:{opts:"=",ngModel:"="},replace:!0,template:function(element,attrs){var xx,defaults={type:"dragNDrop",useUploadButton:"0",classes:{dragText:"jrg-image-upload-drag-text",orText:"jrg-image-upload-or-text",uploadText:"jrg-image-upload-upload-text",browseInput:"jrg-image-upload-browse-input",browseButton:"jrg-image-upload-browse-button",uploadButton:"jrg-image-upload-upload-button"},htmlUploading:"",showProgress:!0,cropAspectRatio:1};void 0!==attrs.htmlUploading&&(defaults.showProgress=!1);for(xx in defaults)void 0===attrs[xx]&&(attrs[xx]="object"==typeof defaults[xx]?{}:defaults[xx]);for(xx in defaults.classes)void 0===attrs.classes[xx]&&(attrs.classes[xx]=defaults.classes[xx]);for(var attrsToInt=["useUploadButton"],ii=0;ii<attrsToInt.length;ii++)attrs[attrsToInt[ii]]=parseInt(attrs[attrsToInt[ii]],10);void 0===attrs.id&&(attrs.id="jrgImageUpload"+Math.random().toString(36).substring(7));var fileTypeDisplay="Image",id1=attrs.id,ids={input:{fileFake:id1+"FileFake",file:id1+"File",byUrl:id1+"ByUrl"},progress:{barInner:id1+"ProgressBarInner",bar:id1+"ProgressBar"},areaSelect:{instId:id1+"AreaSelect"},img:id1+"Img",imgCrop:id1+"ImgCrop"};attrs.ids=ids,jrgImageUploadData[id1]={ids:ids};var htmlDisplay,htmlUrlInstructions;void 0!==attrs.htmlDisplay?(htmlDisplay=attrs.htmlDisplay,htmlDisplay+="<input ng-model='fileFake' id='"+ids.input.fileFake+"' type='hidden' disabled=disabled name='fakeupload' />"):(htmlDisplay="<span class='"+attrs.classes.dragText+"'>Drag "+fileTypeDisplay+" Here</span><br />",htmlDisplay+="<span class='"+attrs.classes.orText+"'>--OR--</span><br />",htmlDisplay+="<span class='"+attrs.classes.uploadText+"'>Upload File:</span><br />",htmlDisplay+="<input ng-model='fileFake' id='"+ids.input.fileFake+"' type='text' disabled=disabled name='fakeupload' class='"+attrs.classes.browseInput+"' /><span class='"+attrs.classes.browseButton+"'>Browse</span>"),htmlUrlInstructions=void 0!==attrs.htmlUrlInstructions?attrs.htmlUrlInstructions:"<span class='jrg-image-upload-by-url-instructions'>1. Right click an image on the web, 2. Choose \"Copy image URL\", 3. Paste it above!</span>",attrs.cropOptions={cropAspectRatio:attrs.cropAspectRatio};var widthAspectDummyPercent=Math.floor(100/attrs.cropOptions.cropAspectRatio);widthAspectDummyPercent=0;var ngShow={dragNDrop:!1,uploadButton:!1};"dragNDrop"==attrs.type&&(ngShow.dragNDrop=!0,attrs.useUploadButton||(ngShow.uploadButton=!1));var html="";return html+="<div class='jrg-image-upload-form-container'>",html+="<form class='jrg-image-upload-form' enctype='multipart/form-data' method='post' action='{{uploadPath}}'>",html+="<div class='jrg-image-upload-fake-input-container' ng-show='"+ngShow.dragNDrop+"'>",html+="<div class='jrg-image-upload-fake-input-container-inner' ng-show='!imgSrc'>",html+="<div class='jrg-image-upload-aspect-ratio-dummy' style='padding-top:"+widthAspectDummyPercent+"%;'></div>",html+="<div class='jrg-image-upload-aspect-ratio-element'>",html+=htmlDisplay,html+="</div>",html+="</div>",html+="<div class='jrg-image-upload-picture-container {{classes.pictureContainer}}' style='z-index:{{zIndex.cropPicture}};' ng-show='{{show.pictureContainer}}'>",html+="<div class='jrg-image-upload-aspect-ratio-dummy' style='padding-top:"+widthAspectDummyPercent+"%;'></div>",html+="<div class='jrg-image-upload-aspect-ratio-element'>",html+="<div class='jrg-image-upload-picture-container-img-outer'>",html+="<div jrg-area-select coords='areaSelectCoords' select-buffer='8' aspect-ratio='"+attrs.cropAspectRatio+"' inst-id='"+attrs.ids.areaSelect.instId+"'>",html+="<img id='{{attrs.ids.img}}' class='jrg-image-upload-picture-container-img' style='z-index:{{zIndex.img}};' ng-src='{{imgSrc}}' />",html+="<img id='{{attrs.ids.imgCrop}}' class='jrg-image-upload-picture-container-img-crop' style='z-index:{{zIndex.imgCrop}};' ng-src='{{imgSrcCrop}}' />",html+="</div>",html+="</div>",html+="</div>",html+="</div>",html+="<input ng-model='file' type='file' name='"+ids.input.file+"' id='"+ids.input.file+"' class='jrg-image-upload-input' style='z-index:{{zIndex.inputUpload}};' />",html+="<div class='jrg-image-upload-picture-container-below {{classes.pictureContainerBelow}}'>",html+="<div class='jrg-image-upload-picture-crop-div {{classes.cropStartBtn}}'><span class='jrg-image-upload-picture-crop-button' ng-click='startCrop({})'>Crop Thumbnail</span></div>",html+="<div class='jrg-image-upload-picture-container-text {{classes.picInstructions}}'>Click or drag onto the picture to change images</div>",html+="<div class='jrg-image-upload-picture-container-text {{classes.cropBtns}}'><div class='jrg-image-upload-picture-crop-button' ng-click='cropCancel({})'>Cancel</div><div class='jrg-image-upload-picture-crop-button' ng-click='crop({})'>Crop</div></div>",html+="<div class='jrg-image-upload-picture-container-text {{classes.cropInstructions}}'>Click and drag on the picture to crop</div>",html+="</div>",html+="<div class='jrg-image-upload-picture-crop-container'>",html+="</div>",html+="</div>",html+="<div class='jrg-image-upload-by-url-container' ng-hide='"+ngShow.dragNDrop+"'>",html+="<span class='jrg-image-upload-by-url-text'>Upload From Other Website</span><br /><br />",html+="<input ng-model='fileByUrl' id='"+attrs.ids.input.byUrl+"' type='text' class='jrg-image-upload-by-url-input' placeholder='Copy & Paste URL here' />",html+=htmlUrlInstructions,html+="</div>",html+="</form>",html+="<div class='jrg-image-upload-upload-upload-button-container' ng-show='"+ngShow.uploadButton+"'><span class='"+attrs.classes.uploadButton+"' ng-click='uploadFile({})'>Upload</span></div>",html+="<div class='jrg-image-upload-notify' ng-show='{{show.notify}}'>"+attrs.htmlUploading+"</div>",html+="<div id='"+attrs.ids.progress.bar+"' class='jrg-image-upload-progress-bar'><div id='"+attrs.ids.progress.barInner+"' class='jrg-image-upload-progress-bar-inner'> </div></div>",html+="<div>{{progressNumber}}</div>",html+="<div>{{fileInfo.name}}</div>",html+="<div>{{fileInfo.size}}</div>",html+="<div>{{fileInfo.type}}</div>",html+="</div>"},link:function(scope,element,attrs){angular.element(document.getElementById(attrs.ids.input.file)).on("change",function(){scope.fileSelected({})})},controller:function($scope,$element,$attrs){function init(){if($scope.areaSelectCoords={},$scope.file="",$scope.fileByUrl="",$scope.imgSrc="",$scope.imgSrcCrop="",$scope.show={notify:!1,pictureContainer:!0,pictureContainerBelow:!1},$scope.classes={pictureContainer:"",pictureContainerBelow:"hidden",cropStartBtn:"",picInstructions:"",cropBtns:"hidden",cropInstructions:"hidden"},$scope.zIndex={inputUpload:2,cropPicture:1,img:2,imgCrop:1},imgInfo={haveCroppedFile:!1},$scope.ngModel&&$scope.ngModel.length>0){$scope.classes.pictureContainer="";var xx,data1={},serverVals1={};for(xx in $scope.opts.imageServerKeys)"imgFileName"==xx&&(serverVals1[xx]=$scope.ngModel);afterComplete({type:"regular",serverVals:serverVals1,fromInit:!0},data1),$timeout(function(){stopCropping({})},100)}else(void 0===$scope.ngModel||$scope.ngModel.length<1)&&clearImage({})}function clearImage(){$scope.imgSrc=0,$scope.imgSrcCrop=0,$scope.classes.pictureContainer="hidden"}function checkFileType(fileName,params){var returnArray={valid:!0,errorMsg:""},fileExtension=getFileExtension(fileName,params);if(params.fileTypes&&("string"==typeof params.fileTypes&&(params.fileTypes="image"==params.fileTypes?["png","jpg","jpeg","bmp","gif"]:"any"),"any"!=params.fileTypes)){returnArray.valid=!1,returnArray.errorMsg="Allowed file types are: ";for(var ii=0;ii<params.fileTypes.length;ii++)returnArray.errorMsg+=params.fileTypes[ii].toLowerCase(),ii<params.fileTypes.length-1&&(returnArray.errorMsg+=", "),params.fileTypes[ii].toLowerCase()==fileExtension&&(returnArray.valid=!0)}return returnArray}function getFileExtension(fileName){var ext=fileName.slice(fileName.lastIndexOf(".")+1,fileName.length).toLowerCase();return ext}function uploadProgress(evt){if(evt.lengthComputable){var percentComplete=Math.round(100*evt.loaded/evt.total);$scope.progressNumber=percentComplete.toString()+"%",document.getElementById($attrs.ids.progress.barInner).style.width=percentComplete.toString()+"%"}else $scope.progressNumber="unable to compute"}function uploadComplete(evt,params){document.getElementById($attrs.ids.progress.barInner).style.width="100%";var ele1=angular.element(document.getElementById($attrs.ids.progress.bar));ele1.addClass("complete"),$scope.progressNumber="";var data=angular.fromJson(evt.target.responseText);afterComplete(params,data)}function afterComplete(params,data){var xx;void 0===params.type&&(params.type="regular"),"crop"==params.type?(imgInfo.haveCroppedFile=!0,$scope.zIndex.imgCrop=2,$scope.zIndex.img=1):($scope.zIndex.imgCrop=1,$scope.zIndex.img=2),$scope.classes.pictureContainer="";var serverVals={};for(xx in $scope.opts.imageServerKeys)serverVals[xx]=void 0!==params.serverVals&&void 0!==params.serverVals[xx]?params.serverVals[xx]:$scope.opts.imageServerKeys[xx].indexOf(".")>-1?jrgImageUploadData.evalArray(data,$scope.opts.imageServerKeys[xx],{}):data[$scope.opts.imageServerKeys[xx]];if($scope.classes.pictureContainerBelow="","regular"==params.type&&(void 0!==serverVals.imgFilePath?imgInfo.imgSrc=serverVals.imgFilePath:void 0!==serverVals.imgFileName&&(imgInfo.imgSrc=$scope.opts.uploadDirectory+"/"+serverVals.imgFileName),void 0!==serverVals.picHeight&&(imgInfo.picHeight=serverVals.picHeight),void 0!==serverVals.picWidth&&(imgInfo.picWidth=serverVals.picWidth),imgInfo.imgSrcCrop=imgInfo.imgSrc,imgInfo.picHeightCrop=imgInfo.picHeight,imgInfo.picWidthCrop=imgInfo.picWidth,void 0!==imgInfo.picHeight&&imgInfo.picHeight||(imgInfo.picHeight=imgInfo.picHeightCrop),void 0!==imgInfo.picWidth&&imgInfo.picWidth||(imgInfo.picWidth=imgInfo.picWidthCrop)),$scope.opts.cropOptions.crop&&imgInfo.haveCroppedFile){var index1=imgInfo.imgSrc.lastIndexOf(".");imgInfo.imgSrcCrop=imgInfo.imgSrc.slice(0,index1)+$scope.opts.cropOptions.cropDuplicateSuffix+imgInfo.imgSrc.slice(index1,imgInfo.imgSrc.length)}$scope.imgSrc=imgInfo.imgSrc,$scope.imgSrcCrop=imgInfo.imgSrcCrop+"?"+Math.random().toString(36).substring(7);var img=new Image;if(img.onload=function(){$scope.imgSrc=img.src,params.imgInfo=imgInfo,imgInfo.picHeightCrop=img.height,imgInfo.picWidthCrop=img.width,void 0!==imgInfo.picHeight&&imgInfo.picHeight||(imgInfo.picHeight=imgInfo.picHeightCrop),void 0!==imgInfo.picWidth&&imgInfo.picWidth||(imgInfo.picWidth=imgInfo.picWidthCrop)},img.src=imgInfo.imgSrc,void 0!==serverVals.imgFileName&&$scope.ngModel!==serverVals.imgFileName&&($scope.ngModel=serverVals.imgFileName),$scope.opts.callbackInfo&&(void 0===$scope.opts.callbackInfo||!params.noCallback)){var args=$scope.opts.callbackInfo.args;args=args.concat(data),$scope.$emit($scope.opts.callbackInfo.evtName,args)}$scope.show.notify=!1,$scope.$$phase||$scope.$root.$$phase||$scope.$apply()}function uploadFailed(){alert("There was an error attempting to upload the file. Please try again or try a different file.")}function uploadCanceled(){alert("The upload has been canceled by the user or the browser dropped the connection.")}function startCropping(){$scope.zIndex.imgCrop=1,$scope.zIndex.img=2,$scope.zIndex.inputUpload=1,$scope.zIndex.cropPicture=2,$scope.classes.cropBtns="",$scope.classes.cropInstructions="",$scope.classes.cropStartBtn="hidden",$scope.classes.picInstructions="hidden"}function stopCropping(){$scope.zIndex.inputUpload=2,$scope.zIndex.cropPicture=1,$scope.classes.cropBtns="hidden",$scope.classes.cropInstructions="hidden",$scope.classes.cropStartBtn="",$scope.classes.picInstructions="",$scope.$broadcast("jrgAreaSelectHide",{instId:$attrs.ids.areaSelect.instId})}function ajaxCall(params){var xx;void 0===params.paramsOrig&&(params.paramsOrig={}),params.paramsOrig.type=params.type;var fd=new FormData;if("regular"==params.type&&void 0!==$scope.opts.postData&&fd.append("postData",$scope.opts.postData),"crop"==params.type&&void 0!==$scope.opts.postDataCrop&&fd.append("postDataCrop",$scope.opts.postDataCrop),"regular"==params.type&&("byUrl"==$attrs.type?fd.append($scope.opts.serverParamNames.byUrl,params.fileVal):fd.append($scope.opts.serverParamNames.file,document.getElementById($attrs.ids.input.file).files[0])),"crop"==params.type&&fd.append("fileName",imgInfo.imgSrc),fd.append("fileData[uploadDir]",$scope.opts.uploadDirectory),void 0!==$scope.opts.cropOptions)for(xx in $scope.opts.cropOptions)fd.append("cropOptions["+xx+"]",$scope.opts.cropOptions[xx]);if(void 0!==params.cropCoords)for(xx in params.cropCoords)fd.append("cropCoords["+xx+"]",params.cropCoords[xx]);if(void 0!==params.fullCoords)for(xx in params.fullCoords)fd.append("fullCoords["+xx+"]",params.fullCoords[xx]);var sendInfo=fd,xhr=new XMLHttpRequest;"regular"==params.type&&$attrs.showProgress&&xhr.upload.addEventListener("progress",uploadProgress,!1),xhr.onload=function(ee){uploadComplete(ee,params.paramsOrig)},xhr.onerror=function(ee){uploadFailed(ee,params.paramsOrig)},xhr.addEventListener("abort",uploadCanceled,!1),"regular"==params.type?xhr.open("POST",$scope.opts.uploadPath):"crop"==params.type&&xhr.open("POST",$scope.opts.uploadCropPath),xhr.setRequestHeader("X-Requested-With","XMLHttpRequest"),xhr.onreadystatechange=function(){4==xhr.readyState&&200!=xhr.status&&uploadFailed("",params.paramsOrig)},xhr.send(sendInfo)}var defaults={cropOptions:jrgImageUploadData.cropOptionsDefault,serverParamNames:{file:"file",byUrl:"fileData[fileUrl]"}};void 0===$scope.opts&&($scope.opts={});for(var xx in defaults)$scope.opts[xx]=void 0===$scope.opts[xx]?defaults[xx]:angular.extend(defaults[xx],$scope.opts[xx]);$scope.opts.cropOptions.cropAspectRatio=$attrs.cropAspectRatio;var imgInfo={haveCroppedFile:!1};$scope.$watch("ngModel",function(newVal,oldVal){angular.equals(oldVal,newVal)||init({})}),$scope.fileSelected=function(params){var file,retArray;if("byUrl"==$attrs.type)file=document.getElementById($attrs.ids.input.byUrl).value,retArray=checkFileType(file,{fileTypes:$scope.opts.fileTypes}),retArray.valid||(document.getElementById($attrs.ids.input.byUrl).value="",alert(retArray.errorMsg));else{if(file=document.getElementById($attrs.ids.input.file).files[0]){var fileSize=0;fileSize=file.size>1048576?(Math.round(100*file.size/1048576)/100).toString()+"MB":(Math.round(100*file.size/1024)/100).toString()+"KB"}file&&(retArray=checkFileType(file.name,{fileTypes:$scope.opts.fileTypes}),retArray.valid?document.getElementById($attrs.ids.input.fileFake).value=document.getElementById($attrs.ids.input.file).value:(document.getElementById($attrs.ids.input.file).value="",alert(retArray.errorMsg)))}$attrs.useUploadButton||"dragNDrop"!=$attrs.type||$scope.uploadFile(params)},$scope.uploadFile=function(params){var fileVal;if($attrs.htmlUploading&&($scope.show.notify=!0),fileVal=void 0!==$attrs.fileUrl?$attrs.fileUrl:"byUrl"==$attrs.type?document.getElementById($attrs.ids.input.byUrl).value:document.getElementById($attrs.ids.input.file).value,fileVal.length>0){if(angular.element(document.getElementById($attrs.ids.progress.barInner)).css({width:"0%"}),$attrs.showProgress){var eleProgressBar=angular.element(document.getElementById($attrs.ids.progress.bar));eleProgressBar.removeClass("complete"),eleProgressBar.addClass("loading")}ajaxCall({type:"regular",paramsOrig:params,fileVal:fileVal})}},$scope.startCrop=function(){startCropping({}),$scope.$broadcast("jrgAreaSelectReInit",{instId:$attrs.ids.areaSelect.instId})},$scope.cropCancel=function(){stopCropping({})},$scope.crop=function(){var cropCoords={},scale=1,fullCoords={};imgInfo.picWidth>$scope.areaSelectCoords.ele.width?scale=$scope.areaSelectCoords.ele.width/imgInfo.picWidth:imgInfo.picHeight>$scope.areaSelectCoords.ele.height&&(scale=$scope.areaSelectCoords.ele.height/imgInfo.picHeight),scale>1?(cropCoords.left=$scope.areaSelectCoords.select.left*scale,cropCoords.top=$scope.areaSelectCoords.select.top*scale,cropCoords.right=$scope.areaSelectCoords.select.right*scale,cropCoords.bottom=$scope.areaSelectCoords.select.bottom*scale,fullCoords.left=$scope.areaSelectCoords.ele.left*scale,fullCoords.top=$scope.areaSelectCoords.ele.top*scale,fullCoords.right=$scope.areaSelectCoords.ele.right*scale,fullCoords.bottom=$scope.areaSelectCoords.ele.bottom*scale):(cropCoords.left=$scope.areaSelectCoords.select.left/scale,cropCoords.top=$scope.areaSelectCoords.select.top/scale,cropCoords.right=$scope.areaSelectCoords.select.right/scale,cropCoords.bottom=$scope.areaSelectCoords.select.bottom/scale,fullCoords.left=$scope.areaSelectCoords.ele.left/scale,fullCoords.top=$scope.areaSelectCoords.ele.top/scale,fullCoords.right=$scope.areaSelectCoords.ele.right/scale,fullCoords.bottom=$scope.areaSelectCoords.ele.bottom/scale),ajaxCall({type:"crop",cropCoords:cropCoords,fullCoords:fullCoords}),stopCropping({})},init({})}}}]).factory("jrgImageUploadData",[function(){var inst={cropOptionsDefault:{crop:!0,cropAspectRatio:1,cropMinHeight:100,cropMinWidth:100,cropMaxHeight:300,cropMaxWidth:300,cropDuplicateSuffix:"_crop"},cropCoords:{left:0,right:0,top:0,bottom:0},cropCurrentImageSrc:"",cropInfoEdit:{JcropApi:!1,cropping:!1},curData:{},evalArray:function(base,keys){"string"==typeof keys&&(keys=keys.split("."));for(var keysCopy=angular.copy(keys);keysCopy.length&&(base=base[keysCopy.shift()]););return base}};return inst}]);