-
-
Save EricSeastrand/8bbedd1f72ba1ec45137819bf41ac3bc to your computer and use it in GitHub Desktop.
Angular Fire Upload tasks
This file contains hidden or 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
pushFileToStorage(fileUpload: FileUpload) { // Pass in a callback as argument | |
const filePath = `${this.basePath}/${fileUpload.file.name}`; | |
const storageRef = ref(this.storage, filePath); | |
const uploadTask = uploadBytesResumable(storageRef, fileUpload.file); | |
uploadTask.on('state_changed', | |
(snapshot) => { | |
// Observe state change events such as progress, pause, and resume | |
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded | |
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; | |
console.log('Upload is ' + progress + '% done'); | |
// ToDo: Should the callback be optional? This will error if it's undefined. | |
handlePercentageChange(progress) // Call the callback | |
switch (snapshot.state) { | |
case 'paused': | |
console.log('Upload is paused'); | |
break; | |
case 'running': | |
console.log('Upload is running'); | |
break; | |
} | |
}, | |
(error) => { | |
alert(error); | |
}, | |
() => { | |
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => { | |
console.log('File available at', downloadURL); | |
fileUpload.url = downloadURL; | |
fileUpload.name = fileUpload.file.name; | |
this.saveFileData(fileUpload); | |
}); | |
}); | |
let handlePercentageChange = function() {} // Default to empty function | |
function subscribeToPercentageChange(newHandler) { | |
handlePercentageChange = newHandler // If somebody subscribes, override default. | |
// ToDo: What happens if another subscriber wants to subscribe? | |
// You'd need to push the handlers to an array, and execute each one. | |
// Consider what happens if 1 handler throws an exception? All will fail. | |
} | |
return { | |
'subscribe': subscribeToPercentageChange | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment