Skip to content

Instantly share code, notes, and snippets.

@adamkdean
Last active August 29, 2015 13:57
Show Gist options
  • Save adamkdean/9366062 to your computer and use it in GitHub Desktop.
Save adamkdean/9366062 to your computer and use it in GitHub Desktop.
LocalFileModule
/*
* 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