Last active
August 29, 2015 13:57
-
-
Save adamkdean/9366062 to your computer and use it in GitHub Desktop.
LocalFileModule
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
/* | |
* LocalFileModule | |
* | |
* This service will, for now, allow you to upload local files and | |
* return a string of what they contain. | |
* | |
*/ | |
angular.module('LocalFileModule', []) | |
.service('localFileService', | |
[function() { | |
var html5fileSupported = (window.File && window.FileReader && window.FileList && window.Blob); | |
var clearFileInput = function(id) { | |
var oldInput = document.getElementById(id), | |
newInput = document.createElement('input'); | |
newInput.type = 'file'; | |
newInput.id = oldInput.id; | |
newInput.name = oldInput.name; | |
newInput.className = oldInput.className; | |
newInput.style.cssText = oldInput.style.cssText; | |
oldInput.parentNode.replaceChild(newInput, oldInput); | |
}; | |
var addUploadCallback = function(id, callback) { | |
document.getElementById(id).addEventListener('change', callback, false); | |
}; | |
var addUploadCallbackAsText = function(id, success, error) { | |
clearFileInput(id); | |
document.getElementById(id).addEventListener('change', function(event) { | |
handleUploadAsText(event, success, error) | |
}, false); | |
}; | |
var handleUploadAsText = function(event, success, error) { | |
var reader = new FileReader(), | |
files = event.target.files; | |
if (files.length > 0) { | |
reader.onload = function(event) { | |
success(event.target.result); | |
}; | |
reader.onerror = function(event) { | |
error(event); | |
}; | |
reader.readAsText(files[0]); | |
} | |
}; | |
return { | |
isSupported: html5fileSupported, | |
addUploadCallback: addUploadCallback, | |
addUploadCallbackAsText: addUploadCallbackAsText | |
} | |
}] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment