In this post we will see how to retrieve image from firebase database in Angular. When you upload any file in Firebase what you can do is to save the file's info into the firebase database, then you can get the list of files from the firebase storage using file's info.
Say for example, you have written below code to upload a file in Firebase. On Success what we are going to is to add
const storageRef = firebase.storage().ref(); // uploads/image.png is harcoded which is basepath/filename // file is the actual file which is uploaded // fileUpload is the object of FileUpload class const upload = storageRef.child('uploads/image.png'.put(fileUpload.file)); // On state changed check if the fileupload is success or failure upload.on(firebase.storage.TaskEvent.STATE_CHANGED, (error) => { console.log(error); }, () => { // On success change the url and name as per the uploaded file // Save it in the database fileUpload.url = uploadTask.snapshot.downloadURL; fileUpload.name = fileUpload.file.name; // db is from AngularFireDatabase this.db.list('uploads/').push(fileupload) } );
Once the upload is completed, you can retrieve the uploaded image from firebase using the database as shown below
// get uploaded files based on the basepath getFileUploads(numberItems): AngularFireList<FileUpload> { return this.db.list('uploads'); }
You can call it as
getFileUploads(6).snapshotChanges().map(actions => { return actions.map(a => ({ key: a.payload.key, ...a.payload.val() })); }).subscribe(fileUploads => { this.fileUploads = fileUploads; });
Thus you will get all the fileuploads added to the base path i.e. uploads.
No comments:
Post a Comment