Coding exercise: create a file upload component in Angular.
Model answer
Use a file input, check type and size for a quick message, send FormData with HttpClient (leave Content-Type alone), and use reportProgress to show progress. The server checks the file again.
@Component({
selector: 'app-upload',
template: `
<input type="file" accept="image/png,image/jpeg" (change)="pick($event)" />
@if (progress() > 0 && progress() < 100) { <progress [value]="progress()" max="100"></progress> }
<p role="status">{{ status() }}</p>`,
})
export class Upload {
private http = inject(HttpClient);
progress = signal(0);
status = signal('');
pick(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0];
if (!file) return;
if (!['image/png', 'image/jpeg'].includes(file.type)) return this.status.set('Only PNG or JPG.');
if (file.size > 2 * 1024 * 1024) return this.status.set('Maximum size is 2 MB.');
const body = new FormData();
body.append('file', file);
this.http.post('/api/upload', body, { reportProgress: true, observe: 'events' }).subscribe({
next: (ev) => {
if (ev.type === HttpEventType.UploadProgress && ev.total) this.progress.set(Math.round((100 * ev.loaded) / ev.total));
if (ev.type === HttpEventType.Response) this.status.set('Uploaded.');
},
error: () => this.status.set('Upload failed.'),
});
}
}Unlike fetch, HttpClient can report upload progress, which is a good point to mention.
Tips
- Mention drag and drop, and checking the real file type on the server.
Practise it yourself in the React and Angular code playground.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in Angular.
- Coding exercise: create a search box with debounce in Angular.
- Coding exercise: fetch API data and display it in a table in Angular.
- Coding exercise: implement pagination in Angular.
- Coding exercise: create a login form with validation in Angular.
- Coding exercise: build a parent-child communication example in Angular.