Created
March 4, 2015 14:08
-
-
Save melloc01/a79de1109b27c44adaaf to your computer and use it in GitHub Desktop.
FileDropzone.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module | |
( | |
'common.dropzone', | |
[ | |
] | |
) | |
.directive | |
( | |
'fileDropzone', | |
function() | |
{ | |
return { | |
restrict: 'A', | |
scope: | |
{ | |
file: '=', | |
fileName: '=' | |
}, | |
link: function(scope, element, attrs) | |
{ | |
var getDataTransfer = function (event) | |
{ | |
return event.dataTransfer || event.originalEvent.dataTransfer; | |
}; | |
var processDragOverOrEnter = function(event) | |
{ | |
if(event) | |
{ | |
if(event.preventDefault) | |
{ | |
event.preventDefault(); | |
} | |
if(event.stopPropagation) | |
{ | |
return false; | |
} | |
getDataTransfer(event).effectAllowed = 'copy'; | |
} | |
return false; | |
}; | |
var validMimeTypes = attrs.fileDropzone; | |
var checkSize = function(size) | |
{ | |
var _ref; | |
if (((_ref = attrs.maxFileSize) === (void 0) || _ref === '') || (size / 1024) / 1024 < attrs.maxFileSize) | |
{ | |
return true; | |
} | |
else | |
{ | |
alert("File must be smaller than " + attrs.maxFileSize + " MB"); | |
return false; | |
} | |
}; | |
var isTypeValid = function(type) | |
{ | |
if ((validMimeTypes === (void 0) || validMimeTypes === '') || validMimeTypes.indexOf(type) > -1) | |
{ | |
return true; | |
} | |
else | |
{ | |
alert("Invalid file type. File must be one of following types " + validMimeTypes); | |
return false; | |
} | |
}; | |
element.bind('dragover', processDragOverOrEnter); | |
element.bind('dragenter', processDragOverOrEnter); | |
element.bind('drop', function(event) { | |
eventHandler(event); | |
}); | |
element.bind('change', function(event) { | |
eventHandler(event); | |
}); | |
function eventHandler(event) | |
{ | |
var file, name, size, type; | |
if (event) | |
{ | |
event.preventDefault(); | |
} | |
var reader = new FileReader(); | |
reader.onload = function(evt) | |
{ | |
if (checkSize(size) && isTypeValid(type)) | |
{ | |
return scope.$apply(function() | |
{ | |
scope.file = evt.target.result; | |
if (angular.isString(scope.fileName)) | |
{ | |
return scope.fileName = name; | |
} | |
}); | |
} | |
}; | |
file = getDataTransfer(event) ? getDataTransfer(event).files[0] : event.target.files[0]; | |
name = file.name; | |
type = file.type; | |
size = file.size; | |
reader.readAsDataURL(file); | |
return false; | |
} | |
} | |
}; | |
} | |
) | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment