How To Connect Image Upload To Firebase Ionic 3
Firebase tin exist used in a lot of means, and too the database the second biggest feature might be its deject storage.
In this tutorial we volition go on with an app from a previous tutorial on using different media files with Ionic. Y'all can grab the code for the previous app and apply the changes of this post, or just wait how the file upload could work in general!
Finally we will be able to capture media files, store them on our device so upload them to Firebase storage!
For this app you will also need a Firebase account and an app inside the panel – both are gratis so go alee and create them!
Preparing our Media App
The showtime change nosotros make to our previous project is adding Firebase, and some other page where nosotros tin display all files that we uploaded. Therefore run within the binder of the previous project:
npm install firebase @ athwart / fire ionic g page cloudList npm install @ ionic - native / in - app - browser ionic cordova plugin add cordova - plugin - inappbrowser |
The InAppBrowser will exist used to showcase that nosotros actually got a real URL to the files after uploading them – of course this is not really mandatory otherwise.
For our simple instance we will also disable the security rules on our Storage inside Firebase, so navigate to Storage -> Rules and commutation the current rules for these, which allow read and write admission to everyone:
rules_version = 'ii' ; service firebase . storage { match / b / { bucket } / o { match / { allPaths = * * } { allow read , write ; } } } |
You should of course change these after testing and have advisable security rules in place in a existent app!
Calculation AngularFire and Firebase
Now information technology'south time to connect our Ionic app to Firebase, and for this you demand the credentials of your Firebase app. You lot can add a new app to your Firebase project by clicking at the peak left on the wheel and so Project settings. At the bottom of that page you tin can edit your apps or add a new web project.
One time you created this yous need to copy the configuration which looks like this:
We can re-create information technology out and paste it into our environments/surround.ts and brand it look like this (only of grade with your values inside):
consign const environment = { production : faux , firebaseConfig : { apiKey : '' , authDomain : '' , databaseURL : '' , projectId : '' , storageBucket : '' , messagingSenderId : '' , appId : '' } } ; |
With that information in place we tin can initialise the AngularFire module inside our app/app.module.ts and also import the AngularFireStorageModule
which is needed to access the storage:
i 2 3 4 5 six vii 8 9 10 11 12 thirteen xiv 15 sixteen 17 xviii nineteen 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 forty 41 42 43 44 | import { NgModule } from '@angular/core' ; import { BrowserModule } from '@athwart/platform-browser' ; import { RouteReuseStrategy } from '@athwart/router' ; import { IonicModule , IonicRouteStrategy } from '@ionic/angular' ; import { SplashScreen } from '@ionic-native/splash-screen/ngx' ; import { StatusBar } from '@ionic-native/status-bar/ngx' ; import { AppComponent } from './app.component' ; import { AppRoutingModule } from './app-routing.module' ; import { ImagePicker } from '@ionic-native/image-picker/ngx' ; import { File } from '@ionic-native/File/ngx' ; import { MediaCapture } from '@ionic-native/media-capture/ngx' ; import { Media } from '@ionic-native/media/ngx' ; import { StreamingMedia } from '@ionic-native/streaming-media/ngx' ; import { PhotoViewer } from '@ionic-native/photo-viewer/ngx' ; import { AngularFireModule } from '@angular/burn' ; import { environment } from '../environments/environs' ; import { AngularFireStorageModule } from '@angular/burn down/storage' ; import { InAppBrowser } from '@ionic-native/in-app-browser/ngx' ; @ NgModule ( { declarations : [ AppComponent ] , entryComponents : [ ] , imports : [ BrowserModule , IonicModule . forRoot ( ) , AppRoutingModule , AngularFireModule . initializeApp ( surround . firebaseConfig ) , AngularFireStorageModule ] , providers : [ StatusBar , SplashScreen , { provide : RouteReuseStrategy , useClass : IonicRouteStrategy } , ImagePicker , MediaCapture , File , Media , StreamingMedia , PhotoViewer , InAppBrowser ] , bootstrap : [ AppComponent ] } ) export class AppModule { } |
Now our app is connected with Firebase and set to upload some files!
Uploading Files to Firebase Storage
In the previous tutorial nosotros captured files and stored them on our device, so we take all data locally bachelor. At present we want to upload a certain file from a path, and nosotros can do this by converting information technology to a Blob!
The Cordova file plugin already comes with a helpful function called readAsArrayBuffer
that will read a local file, but we likewise demand to brand sure that we ready the correct mimetype for the file.
To practice so, we add a simple helper function that checks the extension of the file – of form yous might take dissimilar files so feel gratuitous to extend that function to your needs.
Side by side we create a random id and combine it with a date to create a uniqueish name for our file inside Firebase storage.
The rest becomes super piece of cake: We simply telephone call the upload
function on the AngularFireStorage and pass the new name (or path to the file) plus the blob we created. This volition return an UploadTask
, which offers some absurd functionality like subscribing to the changes in club to display a progress bar!
Now go alee and change your previous app/dwelling/home.page.ts to include the new functionality also:
1 2 3 4 5 six 7 viii nine 10 11 12 thirteen 14 15 16 17 18 nineteen xx 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 twoscore 41 42 43 44 45 46 47 48 49 fifty 51 52 53 54 55 56 57 | // All other imports from before! import { AngularFireStorage } from '@angular/burn/storage' ; export grade HomePage implements OnInit { files = [ ] ; uploadProgress = 0 ; constructor ( private imagePicker : ImagePicker , private mediaCapture : MediaCapture , private file : File , private media : Media , private streamingMedia : StreamingMedia , individual photoViewer : PhotoViewer , private actionSheetController : ActionSheetController , private plt : Platform , private toastCtrl : ToastController , private storage : AngularFireStorage ) { } // All other functionality from before ... async uploadFile ( f : FileEntry ) { const path = f . nativeURL . substr ( 0 , f . nativeURL . lastIndexOf ( '/' ) + 1 ) ; const type = this . getMimeType ( f . name . split ( '.' ) . popular ( ) ) ; const buffer = await this . file . readAsArrayBuffer ( path , f . name ) ; const fileBlob = new Hulk ( [ buffer ] , blazon ) ; const randomId = Math . random ( ) . toString ( 36 ) . substring ( two , 8 ) ; const uploadTask = this . storage . upload ( ` files / $ { new Date ( ) . getTime ( ) } _ $ { randomId } ` , fileBlob ) ; uploadTask . percentageChanges ( ) . subscribe ( change = > { this . uploadProgress = change ; } ) ; uploadTask . then ( async res = > { const toast = await this . toastCtrl . create ( { duration : 3000 , message : 'File upload finished!' } ) ; toast . present ( ) ; } ) ; } getMimeType ( fileExt ) { if ( fileExt == 'wav' ) render { type : 'audio/wav' } ; else if ( fileExt == 'jpg' ) return { type : 'image/jpg' } ; else if ( fileExt == 'mp4' ) render { type : 'video/mp4' } ; else if ( fileExt == 'MOV' ) return { type : 'video/quicktime' } ; } } |
Inside the view we already had a list previously, and we just add the progress bar and another sliding button to perform the upload chore, and then go ahead and change the app/home/habitation.page.html to:
ane two iii four 5 six 7 8 9 ten 11 12 13 fourteen 15 sixteen 17 xviii xix twenty 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | < ion - header > < ion - toolbar colour = "primary" > < ion - title > Ionic Media Capture < / ion - title > < ion - buttons slot = "end" > < ion - push button routerLink = "/cloud-list" > < ion - icon slot = "icon-only" name = "cloud-done" > < / ion - icon > < / ion - button > < / ion - buttons > < / ion - toolbar > < / ion - header > < ion - content > < ion - progress - bar [ value ] = "uploadProgress" colour = "success" > < / ion - progress - bar > < ion - list > < ion - detail - sliding * ngFor = "let f of files" > < ion - item ( click ) = "openFile(f)" > < ion - icon name = "prototype" slot = "start" * ngIf = "f.name.endsWith('jpg')" > < / ion - icon > < ion - icon name = "videocam" slot = "start" * ngIf = "f.proper noun.endsWith('MOV') || f.proper name.endsWith('mp4')" > < / ion - icon > < ion - icon proper name = "mic" slot = "start" * ngIf = "f.name.endsWith('wav')" > < / ion - icon > < ion - label class = "ion-text-wrap" > { { f . proper name } } < p > { { f . fullPath } } < / p > < / ion - label > < / ion - item > < ion - detail - options side = "start" > < ion - item - choice ( click ) = "deleteFile(f)" colour = "danger" > < ion - icon name = "trash" slot = "icon-only" > < / ion - icon > < / ion - detail - option > < / ion - item - options > < ion - detail - options side = "finish" > < ion - item - choice ( click ) = "uploadFile(f)" color = "chief" > < ion - icon name = "cloud-upload" slot = "icon-only" > < / ion - icon > < / ion - particular - pick > < / ion - item - options > < / ion - item - sliding > < / ion - list > < / ion - content > < ion - footer > < ion - toolbar color = "primary" > < ion - button fill = "articulate" expand = "total" color = "light" ( click ) = "selectMedia()" > < ion - icon slot = "outset" name = "document" > < / ion - icon > Select Media < / ion - push > < / ion - toolbar > < / ion - footer > |
Now yous can run your app on a device, capture a media file of any type (that will be stored on the device first) so call the deject upload to send it to Firebase Storage!
You can see the result past going to the Storage expanse of your Firebase app afterwards you uploaded a file.
Working with Files in Firebase Storage
If you also want to list all files in your app that yous've uploaded to Firebase, you tin do information technology every bit well. At the time writing this it was not possible through AngularFire, simply you can besides directly utilise the spider web SDK of Firebase for cases similar this.
All you have to do is call listAll
on the reference to your storage folder and it will render a list of references. These references contain a lot of data, and we just extract the interesting fields and push it to our local array which we will use within our view in the next footstep.
The most interesting part here is perhaps the getDownloadURL
, which returns a Promise. That'due south why we have to wait for it (or use the async pipe in the view, any you prefer), but this volition render the full URL to the hosted file on Firebase!
Go ahead and change your app/deject-listing/cloud-listing.page.ts to:
1 2 3 4 v six seven 8 9 10 eleven 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 forty 41 42 43 44 | import { Component , OnInit } from '@angular/core' ; import { InAppBrowser } from '@ionic-native/in-app-browser/ngx' ; import * as firebase from 'firebase/app' ; @ Component ( { selector : 'app-deject-list' , templateUrl : './deject-listing.page.html' , styleUrls : [ './deject-list.folio.scss' ] } ) export class CloudListPage implements OnInit { cloudFiles = [ ] ; constructor ( individual iab : InAppBrowser ) { } ngOnInit ( ) { this . loadFiles ( ) ; } loadFiles ( ) { this . cloudFiles = [ ] ; const storageRef = firebase . storage ( ) . ref ( 'files' ) ; storageRef . listAll ( ) . so ( issue = > { consequence . items . forEach ( async ref = > { this . cloudFiles . push button ( { name : ref . name , full : ref . fullPath , url : await ref . getDownloadURL ( ) , ref : ref } ) ; } ) ; } ) ; } openExternal ( url ) { this . iab . create ( url ) ; } deleteFile ( ref : firebase . storage . Reference ) { ref . delete ( ) . then ( ( ) = > { this . loadFiles ( ) ; } ) ; } } |
This means we can use this URL in our app to display files directly from Storage, or like we do, even open up an external browser with the URL!
Finally, y'all tin can also call different functions on the reference itself like we do in the delete
function.
To wrap things up, we build a super simple list around the array within the app/cloud-list/cloud-list.folio.html like this:
1 2 3 4 5 6 vii 8 9 10 xi 12 xiii xiv 15 16 17 18 19 20 21 22 23 24 25 26 27 | < ion - header > < ion - toolbar color = "main" > < ion - buttons slot = "start" > < ion - back - button defaultHref = "/" > < / ion - back - push button > < / ion - buttons > < ion - title > Deject Files < / ion - title > < / ion - toolbar > < / ion - header > < ion - content > < ion - list > < ion - item * ngFor = "let f of cloudFiles" > < ion - push slot = "start" ( click ) = "openExternal(f.url)" > < ion - icon name = "open" slot = "icon-merely" > < / ion - icon > < / ion - push > < ion - label class = "ion-text-wrap" > { { f . proper name } } < p > { { f . full } } < / p > < / ion - label > < ion - button slot = "end" ( click ) = "deleteFile(f.ref)" color = "danger" > < ion - icon proper name = "trash" slot = "icon-only" > < / ion - icon > < / ion - push > < / ion - item > < / ion - list > < / ion - content > |
Now you can upload your files, see which files were uploaded, delete them or even employ their full path to the hosted file.
Conclusion
Working with Firebase storage is a great way to hands host different files that your app needs, like user avatars or other uploaded files.
The biggest challenge might really be the conversion from file to hulk, but with the functions of this tutorial you lot should be prepared to handle everything!
Y'all can as well discover a video version of this commodity beneath.
How To Connect Image Upload To Firebase Ionic 3,
Source: https://devdactic.com/upload-ionic-files-firebase-storage/
Posted by: donnersily1998.blogspot.com
0 Response to "How To Connect Image Upload To Firebase Ionic 3"
Post a Comment