Angular File Upload (With Cancel Button)
Sometimes you need to upload a file with the Angular framework.
And send it to a specific API server.
And while the file is being sent you want to give the user the option to cancel the file upload.
So today we're going to learn how to use Angular file input forms, upload a file to a backend API and allow users to cancel the operation.
Step 1: Set Up the Angular File Input
Our first step is to use the HTML file input and bind it's change event.
<input type="file" (change)="onFileSelected($event)" />
And then we need to handle the file selection event inside our components Typescript file.
selectedFile: File | null = null;
onFileSelected(event: Event): void {
const input = event.target as HTMLInputElement;
if (input.files && input.files.length > 0) {
this.selectedFile = input.files[0];
}
}
Step 2: Upload the File to the Backend API
Next we'll need to inject Angular's HttpClient and handle the HTTP request to our API.
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
constructor(private http: HttpClient) {}
Or if you prefer using the inject function.
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
const http = inject(HttpClient);
Now we'll define our upload method that checks if a file is selected. If selected it will use FormData
to upload it via our HTTP client.
uploadRequestSub$: Subscription | undefined = undefined;
uploadFile(): void {
if (!this.selectedFile) {
return;
}
const formData = new FormData();
formData.append('file', this.selectedFile);
this.uploadRequestSub$ = this.http.post('https://api.blackhole.io/upload-file', formData);
this.uploadRequestSub$.subscribe(response => console.log('File uploaded successfully:', response));
}
And now we'll add a button in the HTML template to trigger the file upload.
<button (click)="uploadFile()">Upload File</button>
Step 3: Add ability to cancel upload
Now we'll want to declare a simple cancel function that will cancel the file upload by unsubscribing from the RxJS subscription.
cancelUpload() {
if (this.uploadRequestSub$) {
this.uploadRequestSub$.unsubscribe();
}
}
And add a cancel button to our template.
<button (click)="cancelUpload()">Cancel</button>
Full Example Code
And here is our final code.
Our HTML template file.
<input type="file" (change)="onFileSelected($event)" />
<button (click)="uploadFile()">Upload File</button>
<button (click)="cancelUpload()">Cancel</button>
Along with the Typescript implementation.
import { Component } from '@angular/core';
import { HttpClient, HttpEvent, HttpEventType, HttpRequest } from '@angular/common/http';
import { last, map, tap } from 'rxjs';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html'
})
export class FileUploadComponent {
selectedFile: File | null = null;
uploadRequestSub$: Subscription | undefined = undefined;
constructor(private http: HttpClient) {}
onFileSelected(event: Event): void {
const input = event.target as HTMLInputElement;
if (input.files && input.files.length > 0) {
this.selectedFile = input.files[0];
}
}
uploadFile(): void {
if (!this.selectedFile) {
return;
}
const formData = new FormData();
formData.append('file', this.selectedFile);
this.uploadRequestSub$ = this.http.post('https://api.blackhole.io/upload-file', formData);
this.uploadRequestSub$.subscribe(response => console.log('File uploaded successfully:', response));
}
}
And that, my friend, is how to upload a file with the Angular framework with the option to cancel.
Till next time,
Daniel Kreider