banner



How To Link Firebase Upload File With A Progress View?

If y'all are a novice programmer and want to meet how Ionic and Firebase work together, this tutorial is for you lot. In this tutorial, we volition acquire how to create a file uploading service in Ionic and shop the file/epitome in Firebase storage.

Yous will also learn how to display the file/paradigm uploading file uploading progress with a progress bar.

Firebase is a powerful, flexible and user-friendly database that takes care of most every problem of yours.

Firebase development paradigm is ane of the best; it has an innumerable number of features that make your life like shooting fish in a barrel. Such as File Storage, Hallmark, Hosting, Testing, and many more.

Non just that, but you tin also develop highly scalable apps with the post-obit features:

  • Electronic mail & password, Google, Facebook, and Github authentication
  • Ready-made API
  • Realtime data
  • Robust security
  • Static file hosting
  • File storage supported by Google Cloud Storage

We will create an Ionic project and precisely target image uploading functionality forth with progress indicator. And then, let's get along:

Prepare Ionic Environs

Showtime, install Ionic CLI executing the following control:

                              npm                install                -g @ionic/cli            

Verify Ionic CLI installation:

              ionic --version            

Beginning creating a brand new Ionic projection:

              ionic starting time ionic-firebase-file-upload blank --type=angular            

Get inside the project:

              cd ionic-firebase-file-upload            

Disable Strict Blazon Errors

To go rid from strict type warnings or errors ensure that you set "strictTemplates": imitation under angularCompilerOptions in tsconfig.json file.

Create Firebase Project + Database Set Up

Caput over to console.firebase.google.com, login using electronic mail then click on Add projection.

Setting up Firebase Project

Declare the projection name and click on proceed.

Ionic 6 Firebase Auth Tutorial

Next, click on the denoted icon.

Ionic Firebase Auth Tutorial

Side by side upwardly, provide the App nickname.

Ionic Firebase App Nickname

The credentials which you are seeing copy them we will demand them in a moment.

Firebase Config Keys

Then, click on the "Firestore" bill of fare item.

Configure the database rules and ready information technology "test mode".

Configure Firebase Storage

We might get the permission denied error, to fix this issue, click on the storage -> Rules and replace the existing security rules with the following rule and and then click on the publish push button.

                              rules_version                =                '2'                ;                service                firebase.storage                {                match                                  /b/                                      {bucket}                                    /o                {                match                                  /                                      {allPaths=                    **                    }                                                  {                let                read,                  write                :                if                request.auth                ==                null                ;                }                }                }                          

Annals firebase credentials into the Ionic Angular surroundings file. Add the following code in environment.ts file.

                              // environments/environment.ts                export                const                environment                =                {                production:                false                ,                firebaseConfig:                {                apiKey:                "xxxxxx-xxxxxx_xxxxxxxxxxxxxxxxxx"                ,                authDomain:                "xxxxxx_xxxxxxxxxxxxxxxxxx"                ,                databaseURL:                "xxxxxx_xxxxxxxxxxxxxxxxxx"                ,                projectId:                "xxxxxx_xxxxxxxxxxxxxxxxxx"                ,                storageBucket:                "xxxxxx_xxxxxxxxxxxxxxxxxx"                ,                messagingSenderId:                "xxxxxxxxxxxxxxxxxx"                ,                appId:                "ane:xxxxxxxxxxxxxxxxxx:web:xxxxxxxxxxxxxxxxxx"                }                }                ;                          

Install and Configure Angular Firebase Packet in Ionic

Angular Firebase library constitute the advice between Firebase and Ionic awarding, the package is widely known every bit AngularFire.

Execute the command to install the official Angular library for Firebase.

                              npm                install                firebase @athwart/fire            

Next, register the AngularFire package in Ionic's main app module.

Add the following code in app.module.ts file:

                              import                {                NgModule                }                from                '@athwart/core'                ;                import                {                BrowserModule                }                from                '@angular/platform-browser'                ;                import                {                RouteReuseStrategy                }                from                '@angular/router'                ;                import                {                IonicModule,                IonicRouteStrategy                }                from                '@ionic/angular'                ;                import                {                AppComponent                }                from                './app.component'                ;                import                {                AppRoutingModule                }                from                './app-routing.module'                ;                // Firebase + environment                import                {                AngularFireModule                }                from                '@angular/fire/compat'                ;                import                {                AngularFireStorageModule                }                from                '@athwart/fire/compat/storage'                ;                import                {                AngularFirestoreModule                }                from                '@angular/fire/compat/firestore'                ;                import                {                surround                }                from                '../environments/environment'                ;                                  @                  NgModule                                (                {                declarations:                [AppComponent]                ,                entryComponents:                [                ]                ,                imports:                [                BrowserModule,                IonicModule.                forRoot                (                )                ,                AppRoutingModule,                AngularFireModule.                initializeApp                (environment.firebaseConfig)                ,                AngularFirestoreModule,                AngularFireStorageModule,                ]                ,                providers:                [                {                provide:                RouteReuseStrategy,                useClass:                IonicRouteStrategy                }                ]                ,                bootstrap:                [AppComponent]                ,                }                )                export                grade                AppModule                {                }                          

Build Image Uploading Characteristic

Now every thing has been configured, permit's outset building Ionic/Athwart prototype uploading functionality with Firebase.

We are using the default home component to integrate the file uploading feature, so add the following code in the home.page.ts file.

                              import                {                Component                }                from                '@angular/core'                ;                import                {                Appreciable                }                from                'rxjs'                ;                import                {                finalize,                tap                }                from                'rxjs/operators'                ;                import                {                AngularFireStorage,                AngularFireUploadTask,                }                from                '@angular/fire/compat/storage'                ;                import                {                AngularFirestore,                AngularFirestoreCollection,                }                from                '@angular/fire/compat/firestore'                ;                export                interface                imgFile                {                proper name:                string                ;                filepath:                string                ;                size:                number                ;                }                                  @                  Component                                (                {                selector:                'app-dwelling'                ,                templateUrl:                'home.page.html'                ,                styleUrls:                [                'dwelling.page.scss'                ]                ,                }                )                export                class                HomePage                {                // File upload task                fileUploadTask:                AngularFireUploadTask;                // Upload progress                percentageVal:                Observable<                number                >                ;                // Track file uploading with snapshot                trackSnapshot:                Observable<                any                >                ;                // Uploaded File URL                UploadedImageURL:                Observable<                string                >                ;                // Uploaded epitome drove                files:                Observable<imgFile[                ]                >                ;                // Image specifications                imgName:                string                ;                imgSize:                number                ;                // File uploading status                isFileUploading:                boolean                ;                isFileUploaded:                boolean                ;                individual                filesCollection:                AngularFirestoreCollection<imgFile>                ;                constructor                (                individual                afs:                AngularFirestore,                private                afStorage:                AngularFireStorage                )                {                this                .isFileUploading                =                false                ;                this                .isFileUploaded                =                faux                ;                // Ascertain uploaded files collection                this                .filesCollection                =                afs.                                  collection                                      <imgFile>                                                  (                'imagesCollection'                )                ;                this                .files                =                this                .filesCollection.                valueChanges                (                )                ;                }                uploadImage                (effect:                FileList)                {                const                file                =                event.                item                (                0                )                ;                // Image validation                if                (file.type.                split                (                '/'                )                [                0                ]                !==                'epitome'                )                {                console                .                log                (                'File type is not supported!'                )                ;                render                ;                }                this                .isFileUploading                =                truthful                ;                this                .isFileUploaded                =                faux                ;                this                .imgName                =                file.proper name;                // Storage path                const                fileStoragePath                =                                  `                  filesStorage/                                      ${                    new                    Date                    (                    )                    .                    getTime                    (                    )                    }                                    _                                      ${file.name}                                    `                                ;                // Image reference                const                imageRef                =                this                .afStorage.                ref                (fileStoragePath)                ;                // File upload chore                this                .fileUploadTask                =                this                .afStorage.                upload                (fileStoragePath,                file)                ;                // Prove uploading progress                this                .percentageVal                =                this                .fileUploadTask.                percentageChanges                (                )                ;                this                .trackSnapshot                =                this                .fileUploadTask.                snapshotChanges                (                )                .                pipe                (                finalize                (                (                )                =>                {                // Retreive uploaded image storage path                this                .UploadedImageURL                =                imageRef.                getDownloadURL                (                )                ;                this                .UploadedImageURL.                subscribe                (                (resp)                =>                {                this                .                storeFilesFirebase                (                {                name:                file.name,                filepath:                resp,                size:                this                .imgSize,                }                )                ;                this                .isFileUploading                =                simulated                ;                this                .isFileUploaded                =                truthful                ;                }                ,                (error)                =>                {                console                .                log                (error)                ;                }                )                ;                }                )                ,                tap                (                (snap)                =>                {                this                .imgSize                =                snap.totalBytes;                }                )                )                ;                }                storeFilesFirebase                (image:                imgFile)                {                const                fileId                =                this                .afs.                createId                (                )                ;                this                .filesCollection                .                doc                (fileId)                .                set                (image)                .                then                (                (res)                =>                {                console                .                log                (res)                ;                }                )                .                catch                (                (err)                =>                {                console                .                log                (err)                ;                }                )                ;                }                }                          

Build Custom File Size Pipage Filter

Adjacent, nosotros demand to create the custom pipe filter, information technology volition transform file size data and make it readable. Create dwelling/format-file-size.pipe.ts file within the home directory.

                              import                {Pipage,                PipeTransform}                from                '@angular/core'                ;                const                FILE_SIZE_UNITS                =                [                'B'                ,                'KB'                ,                'MB'                ,                'GB'                ,                'TB'                ,                'PB'                ,                'EB'                ,                'ZB'                ,                'YB'                ]                ;                const                FILE_SIZE_UNITS_LONG                =                [                'Bytes'                ,                'Kilobytes'                ,                'Megabytes'                ,                'Gigabytes'                ,                'Pettabytes'                ,                'Exabytes'                ,                'Zettabytes'                ,                'Yottabytes'                ]                ;                @Pipage                (                {                name:                'formatFileSize'                }                )                export                class                FormatFileSizePipe                implements                PipeTransform                {                transform                (sizeInBytes:                number                ,                longForm:                boolean                )                :                string                {                const                units                =                longForm                ?                FILE_SIZE_UNITS_LONG                :                FILE_SIZE_UNITS                ;                let                power                =                Math.                round                (Math.                log                (sizeInBytes)                /Math.                log                (                1024                )                )                ;                power                =                Math.                min                (power,                units.length                -                ane                )                ;                const                size                =                sizeInBytes                /                Math.                pw                (                1024                ,                power)                ;                // size in new units                const                formattedSize                =                Math.                round                (size                *                100                )                /                100                ;                // proceed upwardly to 2 decimals                const                unit                =                units[ability]                ;                return                                  `                                      ${formattedSize}                                                                                            ${unit}                                    `                                ;                }                }                          

Next, import and register the FormatFileSizePipe custom pipage filter in dwelling house.module.ts file.

                              import                {                NgModule                }                from                '@angular/core'                ;                import                {                CommonModule                }                from                '@angular/common'                ;                import                {                IonicModule                }                from                '@ionic/angular'                ;                import                {                FormsModule                }                from                '@angular/forms'                ;                import                {                HomePage                }                from                './habitation.folio'                ;                import                {                HomePageRoutingModule                }                from                './dwelling house-routing.module'                ;                import                {                FormatFileSizePipe                }                from                './format-file-size.pipe'                ;                @NgModule                (                {                imports:                [                CommonModule,                FormsModule,                IonicModule,                HomePageRoutingModule                ]                ,                declarations:                [                HomePage,                FormatFileSizePipe                ]                }                )                export                course                HomePageModule                {                }                          

Create File Upload aButton

This stride tells you how to create File uploading button and bind the functions to upload and store file in cloud firestore storage.

Add together the following lawmaking in home.folio.html file.

                                                                    <ion-header                  [translucent]                                      =                    "true"                                    >                                                                      <ion-toolbar                  >                                                                      <ion-title                  >                                Ionic Firebase File Upload Demo                                                      </ion-title                  >                                                                      </ion-toolbar                  >                                                                      </ion-header                  >                                                                      <ion-content                  >                                                                      <ion-card                  class                                      =                    "ion-text-heart"                                    *ngIf                                      =                    "!isFileUploading && !isFileUploaded"                                    >                                                                      <ion-card-header                  >                                                                      <ion-card-title                  >                Choose Images to Upload                                      </ion-carte du jour-title                  >                                                                      </ion-card-header                  >                                                                      <ion-card-content                  >                                                                      <ion-button                  color                                      =                    "primary"                                    size                                      =                    "medium"                                    >                                                                      <input                  type                                      =                    "file"                                    (change)                                      =                    "uploadImage($event.target.files)"                                    />                                                                      </ion-button                  >                                                                      </ion-carte du jour-content                  >                                                                      </ion-card                  >                                <!-- File upload progress bar -->                                                      <div                  *ngIf                                      =                    "percentageVal | async as percentage"                                    >                                Progress: {{ per centum | number }}%                                                      <ion-progress-bar                  value                                      =                    "{{ percentage / 100 }}"                                    >                                                                      </ion-progress-bar                  >                                                                      </div                  >                                                                      <div                  *ngIf                                      =                    "trackSnapshot | async as snap"                                    >                                File size: {{ snap.totalBytes | formatFileSize }} Information transfered: {{     snap.bytesTransferred | formatFileSize }}                                                      </div                  >                                                                      </ion-content                  >                                          

Beginning Project

Somewhen, we need to exam the Ionic paradigm uploading characteristic. So, run the following command and outset the application.

                              npm                install                --save-dev @ionic/lab            

Open the app:

              ionic serve -fifty            

The final output:

Ionic 6 Firebase File/Image Upload with Progress Bar Examlpe

Summary

Ultimately, nosotros accept completed this tutorial. In this tutorial we have create Image uploading in Ionic awarding, also learned how to easily store the images in Firebase storage and display file uploading progress with progress bar.

Source: https://www.positronx.io/ionic-firebase-file-image-upload-with-progress-bar-tutorial-with-example/

Posted by: robertrathany.blogspot.com

0 Response to "How To Link Firebase Upload File With A Progress View?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel