Angular File Upload (Complete Tutorial)
Today we're going to learn how to upload a file with the Angular framework.
And send it to a specific API server.
This is the process of allowing a user to select a file and then saving it to a specified API server.
Here's a straightforward guide to using Angular file input forms and uploading a file to a backend API.
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.
uploadFile(): void {
if (!this.selectedFile) {
return;
}
const formData = new FormData();
formData.append('file', this.selectedFile);
this.http.post('https://api.blackhole.io/upload-file', formData).subscribe(
response => console.log('File uploaded successfully:', response),
error => console.error('File upload failed:', error)
);
}
And now we'll add a button in the HTML template to trigger the file upload.
<button (click)="uploadFile()">Upload File</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>
Along with the Typescript implementation.
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html'
})
export class FileUploadComponent {
selectedFile: File | null = null;
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.http.post('<API_ENDPOINT_URL>', formData).subscribe(
response => console.log('File uploaded successfully:', response),
error => console.error('File upload failed:', error)
);
}
}
And that, my friend, is how to upload a file with the Angular framework.
To summarize, here's what we did.
- Create a file input form using an
<input type="file">
element. - Capture the selected file with an Angular component.
- Use
HttpClient
to upload the file to your backend withFormData
. - Handle success and error responses to manage upload feedback (optional).
Till next time,
Daniel Kreider