Image add or file add is a frequent requirement of the application. In this Angular eight tutorial we will study File upload, file importing development and Image Preview. You can observe this tutorial for angular 7 also
Before begin gaining knowledge of file upload, We want a Angular eight Project. If you don’t be aware of how to create a new project. Follow Angular 8 set up information tutorial.
So let’s get started
Create template
First we want to create template. In this template we will create file enter aspect that approves to us to select the file and a button to post the form. To create it open the app.component.html file and put the beneath html on it. Instead of app.component.html you can put on some other element too!
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3>Choose File</h3>
<div class="form-group">
<input type="file" name="image" (change)="fileProgress($event)" />
</div>
<div *ngIf="fileUploadProgress">
Upload progress: {{ fileUploadProgress }}
</div>
<div class="image-preview mb-3" *ngIf="previewUrl">
<img [src]="previewUrl" height="300" />
</div>
<div class="mb-3" *ngIf="uploadedFilePath">
{{uploadedFilePath}}
</div>
<div class="form-group">
<button class="btn btn-primary" (click)="onSubmit()">Submit</button>
</div>
</div>
</div>
</div>
Configure the HttpClientModule
We will use the Angular eight HttpClient
to add the file on the server.
So earlier than writing file add code, first, Open src/app/app.module.ts
then add this import.
import { HttpClientModule } from '@angular/common/http';
Add HttpClientModule
to imports array under @NgModule
imports: [
HttpClientModule
]
Now open the app.component.ts
file and put the beneath code on it
fileData: File = null;
previewUrl:any = null;
fileUploadProgress: string = null;
uploadedFilePath: string = null;
constructor(private http: HttpClient) { }
fileProgress(fileInput: any) {
this.fileData = <File>fileInput.target.files[0];
this.preview();
}
preview() {
// Show preview
var mimeType = this.fileData.type;
if (mimeType.match(/image\/*/) == null) {
return;
}
var reader = new FileReader();
reader.readAsDataURL(this.fileData);
reader.onload = (_event) => {
this.previewUrl = reader.result;
}
}
onSubmit() {
const formData = new FormData();
formData.append('file', this.fileData);
this.http.post('url/to/your/api', formData)
.subscribe(res => {
console.log(res);
this.uploadedFilePath = res.data.filePath;
alert('SUCCESS !!');
})
}
Here you can see the three strategies onSubmit
, preview and fileProgress
. The fileProgress
approach will known as when the person pick out file. It will get the file object of chosen file and save in the fileData
.
The preview
approach will get the statistics from fileData
variable and examine the file and exhibit the picture in our webpage.
The onSubmit
feature will known as when the structure submit. Here we have created a formData
object. We will save the file object to the formData
and then add it to the server by means of Angular eight HttpClient
After the adjustments our app.component.ts
file will appears like this
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpEventType } from '@angular/common/http';
@Component({
selector: 'app-image-upload-with-preview',
templateUrl: './image-upload-with-preview.component.html',
styleUrls: ['./image-upload-with-preview.component.css']
})
export class ImageUploadWithPreviewComponent implements OnInit {
fileData: File = null;
previewUrl:any = null;
fileUploadProgress: string = null;
uploadedFilePath: string = null;
constructor(private http: HttpClient) { }
ngOnInit() {
}
fileProgress(fileInput: any) {
this.fileData = <File>fileInput.target.files[0];
this.preview();
}
preview() {
// Show preview
var mimeType = this.fileData.type;
if (mimeType.match(/image\/*/) == null) {
return;
}
var reader = new FileReader();
reader.readAsDataURL(this.fileData);
reader.onload = (_event) => {
this.previewUrl = reader.result;
}
}
onSubmit() {
const formData = new FormData();
formData.append('file', this.fileData);
this.http.post('url/to/your/api', formData)
.subscribe(res => {
console.log(res);
this.uploadedFilePath = res.data.filePath;
alert('SUCCESS !!');
})
}
}
Now you can add the file, But in some case you want greater control
Progress Event
If you are dealing with the huge file or You may also favor to exhibit growth to user, Angular 8 httpClient
offers you the development status.
First of all open the app.component.ts
file and put the under import
import { HttpClient, HttpEventType } from '@angular/common/http';
Then you simply need to add reportProgress to real and set the look at to occasions in the config like we have below. You will get all the activities on subscribe
onSubmit() {
const formData = new FormData();
formData.append('files', this.fileData);
this.fileUploadProgress = '0%';
this.http.post('https://us-central1-tutorial-e6ea7.cloudfunctions.net/fileUpload', formData, {
reportProgress: true,
observe: 'events'
})
.subscribe(events => {
if(events.type === HttpEventType.UploadProgress) {
this.fileUploadProgress = Math.round(events.loaded / events.total * 100) + '%';
console.log(this.fileUploadProgress);
} else if(events.type === HttpEventType.Response) {
this.fileUploadProgress = '';
console.log(events.body);
alert('SUCCESS !!');
}
})
}