In Previous post we successfully uploaded the user files to our cloud storage, but we haven't worked on what will happen after the file is uploaded.
Uploading Snapshot
Like every other firebase service we have used by now cloud storage also have snapshots, we can use it to check How much data is uploaded and also trigger some function as it completes.
If you don't know what are snapshots then no problems, it's just
a fancy term to given to changes that occur in firebase.
Read previous posts.
Subscribing to snapshot
To start getting snapshots first change the fileRef.put()
into a variable.
var task = fileRef.put(file);
After changing it to a variable subscribe to the on snapshot it will give us the changes as file uploads.
uploadTask.on('state_changed',
(snapshot) => {
// Handle upload Progress
},
(error) => {
// Handle unsuccessful upload
},
() => {
//Handle complete upload
}
);
Use the same order to create function,
- progress
- error
- complete
getting a progress bar
We can get how much file is uploaded by simply using (snapshot.bytesTransferred / snapshot.totalBytes) * 100
this will give us the percentage of data transferred then we can easily change the style of progress bar.
(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
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
const upProgress = document.getElementById('upProgress');
upProgress.style.width = progress + '%';
}
Getting the file link
In order to display the file we should have a link using which we can access files we can get that link in the complete
part of function.
() => {
// Handle successful uploads on complete
task.snapshot.ref.getDownloadURL().then((downloadURL) => {
console.log('File available at', downloadURL);
});
}
What Next:
In the next post we will see how to store these file data in the firestore database and display it on the main feed
Top comments (0)