Firstly Install
Firebase and AngularFire from NPM in
your apps and it allow us to easily and securely manage a Cloud Storage bucket.
The Firebase
is a server-less ways to upload and download binary files straight from the
browsers-
npm i firebase angularfire2
Add Firebase and AngularFire in your NgModule –
//Import AngularFire in angular 5+ apps
import { AngularFireModule } from 'angularfire2/angularfire2';
import { AngularFireStorage, AngularFireStorageModule } from 'angularfire2/storage';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
UserComponent
],
imports: [
BrowserModule,
AngularFireModule.initializeApp({
apiKey: "<your-api-key>",
authDomain: "<your-auth-domain>",
storageBucket: "<project-id>.appspot.com",
projectId: "<your-project-id>",
}),
AngularFireStorageModule,
FormsModule,
HttpClientModule,
RouterModule.forRoot([
{ path: '', component: AppComponent, pathMatch: 'full', canActivate: [AuthGuard]},
{ path: 'user', component: UserComponent, canActivate: [AuthGuard]},
{ path: 'login', component: LoginComponent}])
],
providers: [ ErrorLoggService, // register global
error log service
GlobalErrorHandler,// register global
error handler
EmployeeService, // register
Employee service
ValidationService, //register
Validation Service
AuthenticationService, //register
Authentication Service
UserService],//register User
Service
bootstrap: [AppComponent]
})
export class AppModule { }
In the last, inject the AngularFireStorage module
into your app component –
import { Component } from '@angular/core';
import {HttpClientModule} from "@angular/common/http";
import { AngularFireStorage } from 'angularfire2/storage';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
//initialize constructor
constructor(private ngFireStorage: AngularFireStorage) { }
//Upload method for upload files from
Cloud Storage
upload(event) {
this.ngFireStorage.upload('/User/uploadFile/img', event.target.files[0]);
}
}
And HTML and CSS components -
<!-- File uploads using AngularFire-->
<h3>File uploads using
AngularFire</h3>
<label for="file" custom-file-upload>Select File -</label>
<input type="file" (change)="upload($event)" accept=".png,.jpg,.jpeg,.gif" class="inputfile"/>
The file uploads control -
<input type="file">
Restricts file uploads -
Secure your storage bucket you need to write rules that only allow images to be
uploaded at the /images path.
The Result looks like –