Angular 16 file upload example; In this tutorial, you will learn step by step how to upload files in angular 16 projects using rest web APIs.
Angular 16 File Upload Example Tutorial
Steps to upload files in angular 16 projects using rest web apis:
- Step 1 – Setup the Angular Project
- Step 2 – Create the File Upload Component
- Step 3 – Implement the File Upload Logic
- Step 4 – Create the File Upload Template
- Step 5 – Add Some Styling (Optional)
- Step 6 – Use the File Upload Component
Step 1 – Setup the Angular Project
First of all, open your command prompt or cmd and execute the following command on it to install & create a new Angular project using the Angular CLI:
ng new file-upload-tutorial cd file-upload-tutorial
Step 2 – Create the File Upload Component
Now, you need to create file upload components in your project. So open cmd and execute the following command into it to generate a new component to handle the file upload functionality:
ng generate component file-upload
Step 3 – Implement the File Upload Logic
Next, Open the file-upload.component.ts
file and implement the following logic:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent {
selectedFile: File | null = null;
filePreview: string | ArrayBuffer | null = null;
constructor(private http: HttpClient) {}
onFileSelected(event: Event): void {
const inputElement = event.target as HTMLInputElement;
if (inputElement.files && inputElement.files.length) {
this.selectedFile = inputElement.files[0];
this.previewFile();
}
}
private previewFile(): void {
const reader = new FileReader();
reader.onload = (e) => {
this.filePreview = e.target?.result;
};
reader.readAsDataURL(this.selectedFile as Blob);
}
uploadFile(): void {
if (!this.selectedFile) {
return;
}
const formData = new FormData();
formData.append('file', this.selectedFile);
// Replace 'http://localhost:5000/upload' with your server's endpoint for file upload
const uploadUrl = 'http://localhost:5000/upload';
this.http.post(uploadUrl, formData).subscribe(
(response: any) => {
console.log('Upload successful:', response);
// Implement any further actions or notifications for successful upload
},
(error) => {
console.error('Upload error:', error);
// Implement any error handling or notifications for failed upload
}
);
}
}
Step 4 – Create the File Upload Template
Next, Open the file-upload.component.html
file and add the following code:
<div>
<input type="file" (change)="onFileSelected($event)" accept=".jpg, .jpeg, .png">
<br>
<div *ngIf="filePreview">
<img [src]="filePreview" alt="Selected File Preview" style="max-width: 300px;">
</div>
<br>
<button (click)="uploadFile()" [disabled]="!selectedFile">Upload File</button>
</div>
Step 5 – Add Some Styling (Optional)
If you want to add some basic styling, open the file-upload.component.css
file and add your styles.
Step 6 – Use the File Upload Component
Now, you need to use the file upload component, so open app.component.html
file and use the FileUploadComponent
like following:
<div style="text-align: center;">
<h1>Angular 16 File Upload Tutorial - Tutsmake.com</h1>
<app-file-upload></app-file-upload>
</div>
Step 7 – Run the Application
Execute the following commands on cmd to start the angular project:
ng serve
Visit http://localhost:4200
in your browser, and you should see the file upload component with a file input and an “Upload File” button. When you select a file, it will display a preview, and when you click the “Upload File” button, you can implement the server-side logic to handle the uploaded file.
Conclusion
Congratulations! You have successfully learned how to implement a file upload in Angular 16 projects with FileReader API.