Skip to content

Instantly share code, notes, and snippets.

@tianweiliu
Last active July 11, 2018 01:07
Show Gist options
  • Save tianweiliu/6594f6cc09d0e5a3ef6c704db6d2f97a to your computer and use it in GitHub Desktop.
Save tianweiliu/6594f6cc09d0e5a3ef6c704db6d2f97a to your computer and use it in GitHub Desktop.
angular factory for angular firebase upload
.factory('$firebaseStorage', ['$q', function($q) {
var $firebaseStorage = {
_ref: firebase.storage().ref(),
upload: function(_path, _file, _onProgress) {
return $q(function(resolve, reject) {
if (!_path) {
reject(new Error('no path'));
}
else if (!_file) {
reject(new Error('no file'));
}
else {
var storagePath = _path + _file.name;
var storageRef = $firebaseStorage._ref.child(storagePath);
var uploadTask = storageRef.put(_file);
uploadTask.on('state_changed',
function(snapshot) {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
// Put $scope.$digest() in the callback to update view
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
if (_onProgress) {
_onProgress(progress);
}
}, function(error) {
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
reject(error);
}, function() {
// Upload completed successfully, now we can get the download URL
// Custom Metadata
/*
storageRef.updateMetadata({
customMetadata: {
'fileName:' : _file.name
}
});
*/
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
resolve(downloadURL);
});
});
}
});
}
};
return $firebaseStorage;
}]);
@tianweiliu
Copy link
Author

Updated for firebase js sdk ^5.0 (downloadURL now needs to be retrieved in a promise function), according to https://firebase.google.com/docs/storage/web/upload-files

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment