Upload Files from Angular to Firebase Storage
Fireship
UPDATE Watch the latest store video here: https://youtu.be/wRWZQwiNFnM
Full Lesson: https://angularfirebase.com/lessons/angular-file-uploads-to-firebase-storage/
In this episode we are going to implement file uploads with Angular and Firebase Storage. File storage is currently unsupported in the AngularFire2 package, but it's still possible to use Firebase storage by interacting directly with the Firebase Web API. We're still going use AngularFire2 for saving information about file uploads to the realtime database, such as the file name and its URL location.
Step 1 - Generate the Files
The structure of this feature is very similar to the Angular Firebase CRUD lesson, so make sure to check that out. It is just form that accepts files, uploads them to the storage bucket, then renders the details to a list.
ng g service uploads/shared/upload ng g class uploads/shared/upload ng g component uploads/uploads-list ng g component uploads/upload-detail ng g component uploads/upload-form
Step 2 - Define the Upload Class
The upload class will be used by the service. Notice it has a constructor for the file
attribute, which has a type of File
. This class is built into JavaScript and it defines files that are passed via HTML from inputs.
Step 3 - Build the Upload Service
The service needs to upload the file to Firebase Storage then save details about the file to the realtime database. First let's add the necessary imports import, including the Firebase API, and declare the variables.
Here's the push upload function works step-by-step.
- First, Establish a reference to the firebase storage bucket.
- Second, define the
uploadTask
as a promise to put the file in storage. - Third, monitor the uploadTask event using the
.on
function. - Last, handle the events of in progress, success, and error.
When the upload is in progress we will take a snapshot to get the number of bytes transferred. Using some simple math, we convert it to a percentage to display a progress bar for the user.
When the upload is complete, we update the database.
Before moving to the components, we need a way to delete files. Deleting a file only requires a reference to its location. Because we saved the name of the file to the database, we can use it to locate the file in storage and delete it. Here's the code to delete files from both firebase storage and the realtime database.
Step 4 - Build the Upload Form Component
Now we need to give users a way to choose files and upload or delete them. Let’s start with the UploadFormComponent because that is where most of the action is happening.
When a user selects files in an HTML file input, it fires the change event. Our template will listen the change event, then pass the event to our component, which contains ... https://www.youtube.com/watch?v=5qoU1EirSmo
17039921 Bytes