Uploading images in Angular
This article describes the following:
- Use Angular to upload images in four different styles.
- Display a progress bar while images are uploading.
- After uploading is complete, the image upload completion message will be displayed.
Uploading images in Angular
Images are the basic part of any web application and every website has images. In this tutorial, we will learn how to upload images in Angular in different ways.
Let us create a new application using the following command.
# angular
ng new my-app
After creating our new application in Angular, we will go to our application directory using this command.
# angular
cd my-app
Now, let's run our application to check if all dependencies are installed correctly.
# angular
ng serve --open
We will import the library and set up the component for our file uploader.
# angular
import { Component, VERSION } from '@angular/core';
import {HttpClientModule, HttpClient, HttpRequest, HttpResponse, HttpEventType} from '@angular/common/http';
@Component({
selector: 'my-app',
template: `
<input type="file" accept=".jpg,.png" class="button" (change)="upload($event.target.files)" />
<p>Upload Percent: {{percentDone}}% </p> <br />
<ng-container *ngIf="uploadSuccess" class="success">
<p class="sucess">Upload Successful</p>
</ng-container>
`,
styleUrls: ['./app.component.css'],
})
Exporting components and declaring variables in Angular
We'll export our and and declare AppComponent
variables as and as . We'll also declare a constructor which calls .percentDone
number
UploadSuccess
boolean
HttpClient
# angular
export class AppComponent {
percentDone: number;
uploadSuccess: boolean;
constructor(private http: HttpClient) {}
Basic upload of multiple images in Angular
There are 4 different styles of image upload in Angular; basic upload of multiple images is one of them. You can upload multiple images in this style without showing a progress bar for the images.
basicUploadImage(files: File[]) {
var formData = new FormData();
Array.from(files).forEach((f) => formData.append('file', f));
this.http.post('https://file.io', formData).subscribe((event) => {
console.log('done');
});
}
We are sending https://file.io
an upload request to , which can be changed with the backend server URL. The backend server will receive the uploaded image data and will send a URL to the uploaded file.
Basic upload of a single image in Angular
The second way to upload images in Angular is the basic upload of image files. In this style, the user can upload only one image at a time.
This style also does not show progress while uploading images.
basicUploadSingleImage(file: File) {
this.http.post('https://file.io', file).subscribe((event) => {
console.log('done');
});
}
Upload and progress of multiple images in Angular
The third way to upload images in Angular is to upload multiple images with progress bar. User can upload multiple images and the progress bar shows the percentage uploaded in this style.
uploadImageAndProgress(files: File[]) {
console.log(files);
var formData = new FormData();
Array.from(files).forEach((f) => formData.append('file', f));
this.http.post('https://file.io', formData, {
reportProgress: true,
observe: 'events',
})
.subscribe((event) => {
if (event.type === HttpEventType.UploadProgress) {
this.percentDone = Math.round((100 * event.loaded) / event.total);
} else if (event instanceof HttpResponse) {
this.uploadSuccess = true;
}
});
}
Single image upload and progress in Angular
The fourth style of image upload in Angular is Single Image with Progress Bar. User can upload a single image with a progress bar showing the percentage of uploading in this style.
uploadAndProgressSingleImage(file: File) {
this.http
.post('https://file.io', file, {
reportProgress: true,
observe: 'events',
})
.subscribe((event) => {
if (event.type === HttpEventType.UploadProgress) {
this.percentDone = Math.round((100 * event.loaded) / event.total);
} else if (event instanceof HttpResponse) {
this.uploadSuccess = true;
}
});
}
Calling upload function in Angular
We have added four upload functions in Angular; we can call our upload functions with the required styles.
uploadImage(files: File[]) {
this.uploadImageAndProgress(files);
}
Output:
Summary
We discussed four different styles of image uploading in Angular and how to upload
call them in our function. The complete code is as follows.
import { Component, VERSION } from '@angular/core';
import {
HttpClientModule,
HttpClient,
HttpRequest,
HttpResponse,
HttpEventType,
} from '@angular/common/http';
@Component({
selector: 'my-app',
template: `
<input type="file" accept=".jpg,.png" class="button" (change)="uploadImage($event.target.files)" />
<p>Upload Percent: {{percentDone}}% </p> <br />
<ng-container *ngIf="uploadSuccess" class="success">
<p class="sucess">Upload Successful</p>
</ng-container>
`,
styleUrls: ['./app.component.css'],
})
export class AppComponent {
percentDone: number;
uploadSuccess: boolean;
constructor(private http: HttpClient) {}
uploadImage(files: File[]) {
this.uploadImageAndProgress(files);
}
basicUploadImage(files: File[]) {
var formData = new FormData();
Array.from(files).forEach((f) => formData.append('file', f));
this.http.post('https://file.io', formData).subscribe((event) => {
console.log('done');
});
}
basicUploadSingleImage(file: File) {
this.http.post('https://file.io', file).subscribe((event) => {
console.log('done');
});
}
uploadImageAndProgress(files: File[]) {
console.log(files);
var formData = new FormData();
Array.from(files).forEach((f) => formData.append('file', f));
this.http.post('https://file.io', formData, {
reportProgress: true,
observe: 'events',
})
.subscribe((event) => {
if (event.type === HttpEventType.UploadProgress) {
this.percentDone = Math.round((100 * event.loaded) / event.total);
} else if (event instanceof HttpResponse) {
this.uploadSuccess = true;
}
});
}
uploadAndProgressSingleImage(file: File) {
this.http
.post('https://file.io', file, {
reportProgress: true,
observe: 'events',
})
.subscribe((event) => {
if (event.type === HttpEventType.UploadProgress) {
this.percentDone = Math.round((100 * event.loaded) / event.total);
} else if (event instanceof HttpResponse) {
this.uploadSuccess = true;
}
});
}
}
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Setting default option value for Select From Typescript in AngularJs
Publish Date:2025/04/18 Views:185 Category:Angular
-
select Is an HTML tag that contains n an option subtag that contains a value attribute. This tutorial guide will provide how to select default option value from TypeScript in AngularJs if the user does not select any specific defined value.
Enabling HTML5 mode in AngularJS
Publish Date:2025/04/18 Views:148 Category:Angular
-
This article will guide you through enabling HTML5 mode with deep linking on your AngularJS application. Using HTML5 mode in AngularJS $locationProvider.html5Mode pushState is a way to tell the browser that it needs to use HTML5 mode for UR
Loading spinner in AngularJs
Publish Date:2025/04/18 Views:133 Category:Angular
-
We will cover how to add a loading spinner while the request is loading and stop the loader while data is loading in AngularJs. Loading spinner in AngularJs Loaders are a part of web applications to make them user-friendly and improve the u
Showing and hiding in Angular
Publish Date:2025/04/18 Views:91 Category:Angular
-
We will walk through examples of showing and hiding components or elements in Angular. Showing and hiding in Angular While developing business applications we need to hide some data based on user roles or conditions. We have to display the
Downloading files in Angular
Publish Date:2025/04/18 Views:164 Category:Angular
-
We will look at how to download a file in Angular by clicking a button and show an example. File downloading in Angular Downloading files in Angular is very easy. We can use HTML5 download attributes to download files. # angular a href = "F
Drag and drop in Angular
Publish Date:2025/04/18 Views:187 Category:Angular
-
We will introduce @angular/cdk/drag-drop the module to accomplish drag and drop in angular. We will also walk through some examples of drag and drop in Angular. Drag and drop in Angular @angular/cdk/drag-drop The module provides you with a
Use TypeScript's getElementById replacement in Angular
Publish Date:2025/04/18 Views:196 Category:Angular
-
This tutorial guide provides a brief description of replacing AngularJS with TypeScript document.getElementById . This also provides getElementById the best practices for using in Angular with code examples. We will also see the use of DOM
Using ngSwitch in Angular
Publish Date:2025/04/18 Views:194 Category:Angular
-
In common programming languages, you have heard and used switch the statement at least once. Statements are used to execute blocks of code when there are many if pre statements , we convert these pre statements into pre statements to save t
Adding classes in Angular
Publish Date:2025/04/18 Views:139 Category:Angular
-
We will cover different methods like className and ngClass to add static or dynamic classes in Angular. We will also cover how to toggle classes in Angular. Adding static or dynamic classes in Angular Classes are the main part of any web ap