Sub topic 13
Tracking Upload and Download Progress
Most HTTP calls finish quickly enough that a spinner is all the feedback a user needs. Large file uploads and report downloads are different. Users want to see how far along a transfer is, and they want a way to cancel it. This chapter shows how to ask HttpClient for progress events, turn them into a percentage, display that percentage in a component, and test the result.
This chapter assumes you have read the earlier chapters on typed requests, the observe option and interceptors. It also assumes you know discriminated unions in TypeScript and can use the RxJS map and filter operators.
Turning on progress events
By default, HttpClient emits a single value: the response body. Progress reporting needs two options together:
reportProgress: truetells the HTTP backend to listen for progress notifications from the browser.observe: 'events'changes the return type toObservable<HttpEvent<T>>, so every event in the request's life reaches your code, not only the body.
If you set reportProgress without observe: 'events', you still receive only the body. The progress events are produced and then thrown away.
import { HttpClient, HttpEvent } from '@angular/common/http';
import { inject } from '@angular/core';
import { Observable } from 'rxjs';
const http = inject(HttpClient); // inside an injection context
const events$: Observable<HttpEvent<{ id: string }>> = http.post<{ id: string }>(
'/api/files',
new FormData(),
{ reportProgress: true, observe: 'events' }
);http.request() gives the same result. You build an HttpRequest object yourself with new HttpRequest('POST', url, body, { reportProgress: true }) and pass it in. http.request() always returns events, so you don't need observe there. The method-specific form shown above is easier to read and keeps the body type, so this chapter uses it.
The event sequence
HttpEvent<T> is a union type. Its type property holds a value from the HttpEventType enum, and TypeScript narrows the event to the matching interface when you check type.
| `HttpEventType` | Interface | When it fires | Useful fields |
|---|---|---|---|
| `Sent` | `HttpSentEvent` | Once, when the request is dispatched | none |
| `UploadProgress` | `HttpUploadProgressEvent` | Repeatedly while the body is sent | `loaded`, `total?` |
| `ResponseHeader` | `HttpHeaderResponse` | Once, when status and headers arrive | `status`, `headers` |
| `DownloadProgress` | `HttpDownloadProgressEvent` | Repeatedly while the body is received | `loaded`, `total?`, `partialText?` |
| `Response` | `HttpResponse<T>` | Once, when the request completes | `body`, `status`, `headers` |
| `User` | `HttpUserEvent<T>` | Only when an interceptor emits a custom event | custom |
The total field is optional, and this causes the most common bug in progress code. During uploads, the browser almost always knows the body size, so total is set. During downloads, total comes from the Content-Length response header. Servers that stream data or use chunked transfer encoding often leave that header out. Compressed responses can also report a Content-Length that doesn't match the decoded byte count. If your code divides by total without checking it, you get NaN or Infinity.
A typed upload service
Raw HttpEvent values are awkward to handle in a template. A cleaner design keeps the event handling in the service and maps it to a small state type that the component can render directly.
// upload.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpEvent, HttpEventType } from '@angular/common/http';
import { Observable, filter, map } from 'rxjs';
export interface UploadResult {
id: string;
url: string;
}
export type UploadState =
| { kind: 'pending' }
| { kind: 'progress'; loaded: number; percent: number | null }
| { kind: 'done'; result: UploadResult };
function toUploadState(event: HttpEvent<UploadResult>): UploadState | null {
switch (event.type) {
case HttpEventType.Sent:
return { kind: 'pending' };
case HttpEventType.UploadProgress: {
const percent = event.total
? Math.round((100 * event.loaded) / event.total)
: null;
return { kind: 'progress', loaded: event.loaded, percent };
}
case HttpEventType.Response:
return { kind: 'done', result: event.body as UploadResult };
default:
return null; // ignore ResponseHeader, DownloadProgress and User events
}
}
@Injectable({ providedIn: 'root' })
export class UploadService {
private readonly http = inject(HttpClient);
upload(file: File): Observable<UploadState> {
const formData = new FormData();
formData.append('file', file, file.name);
return this.http
.post<UploadResult>('/api/files', formData, {
reportProgress: true,
observe: 'events'
})
.pipe(
map(toUploadState),
filter((state): state is UploadState => state !== null)
);
}
}Don't set a Content-Type header for FormData bodies. The browser has to write the multipart boundary into that header itself, and a manual value removes it, so the server can't parse the body.
Showing progress and cancelling
The component subscribes, stores the latest state in a signal, and keeps the Subscription so the user can cancel. When you unsubscribe from an HttpClient Observable, Angular aborts the underlying request. That is all cancellation takes.
// file-upload.component.ts
import { Component, DestroyRef, inject, signal } from '@angular/core';
import { Subscription } from 'rxjs';
import { UploadService, UploadState } from './upload.service';
@Component({
selector: 'app-file-upload',
template: `
<input type="file" (change)="onFileSelected($event)" />
@switch (state()?.kind) {
@case ('pending') { <p>Starting upload…</p> }
@case ('progress') {
@if (percent() !== null) {
<progress max="100" [value]="percent()"></progress> {{ percent() }}%
} @else {
<progress></progress> {{ loaded() }} bytes sent
}
<button type="button" (click)="cancel()">Cancel</button>
}
@case ('done') { <p>Uploaded.</p> }
}
@if (error()) { <p role="alert">{{ error() }}</p> }
`
})
export class FileUploadComponent {
private readonly uploadService = inject(UploadService);
private subscription?: Subscription;
readonly state = signal<UploadState | null>(null);
readonly percent = signal<number | null>(null);
readonly loaded = signal(0);
readonly error = signal<string | null>(null);
constructor() {
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
}
onFileSelected(event: Event): void {
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) return;
this.cancel();
this.error.set(null);
this.subscription = this.uploadService.upload(file).subscribe({
next: s => {
this.state.set(s);
if (s.kind === 'progress') {
this.percent.set(s.percent);
this.loaded.set(s.loaded);
}
},
error: () => {
this.state.set(null);
this.error.set('Upload failed.');
}
});
}
cancel(): void {
this.subscription?.unsubscribe();
this.subscription = undefined;
this.state.set(null);
}
}An indeterminate <progress> element, one with no value, covers the case where total is unknown. Showing a percentage you can't calculate would mislead the user.
Download progress
Downloads use the same options. The body is usually a Blob, so you set responseType: 'blob', and the resulting events are typed HttpEvent<Blob>.
// report.service.ts
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpEventType } from '@angular/common/http';
import { Observable, filter, map } from 'rxjs';
export type DownloadState =
| { kind: 'progress'; percent: number | null }
| { kind: 'done'; blob: Blob };
@Injectable({ providedIn: 'root' })
export class ReportService {
private readonly http = inject(HttpClient);
download(reportId: string): Observable<DownloadState> {
return this.http
.get(`/api/reports/${reportId}`, {
responseType: 'blob',
reportProgress: true,
observe: 'events'
})
.pipe(
map((event): DownloadState | null => {
if (event.type === HttpEventType.DownloadProgress) {
const percent = event.total
? Math.round((100 * event.loaded) / event.total)
: null;
return { kind: 'progress', percent };
}
if (event.type === HttpEventType.Response && event.body) {
return { kind: 'done', blob: event.body };
}
return null;
}),
filter((s): s is DownloadState => s !== null)
);
}
}partialText is set only when responseType is 'text'. It holds the text received so far, which can be useful for streaming logs. With 'blob', 'json' or 'arraybuffer', you get the body only in the final Response event.
Gotchas and failure modes
The fetch backend does not report upload progress
provideHttpClient(withFetch()) replaces XMLHttpRequest with the Fetch API. The Fetch API has no upload progress hook, so UploadProgress events never fire. The fetch backend does emit DownloadProgress by reading the response stream. If you need upload progress in an app that uses withFetch(), you can't switch backends for a single request. You have to remove withFetch() or accept the indeterminate indicator.
Interceptors that assume a response
An interceptor sees every event in the stream. An interceptor written as map(res => (res as HttpResponse<unknown>).body) breaks the stream. So does one that filters for HttpResponse without passing the other events through. Check event.type or use instanceof HttpResponse before you touch body. Pass all other events through unchanged.
Retrying a large upload
retry(2) resubscribes, and resubscribing resends the whole body from byte zero. The progress bar then jumps back to 0%. For large files, either drop the retry or reset the displayed progress when the Sent event arrives again. For very large files, use a resumable or chunked upload protocol on the server instead.
Progress is not completion
UploadProgress reaching 100% means the browser finished sending the bytes. The server may still be scanning or storing the file. Treat only the Response event as success, and show a "processing" state between the two if the gap is noticeable.
Testing progress events
TestRequest.event() pushes any HttpEvent into the stream before you call flush(). You can use it to check your mapping logic without a real network.
// upload.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { HttpEventType, provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { UploadService, UploadState } from './upload.service';
describe('UploadService', () => {
let service: UploadService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()]
});
service = TestBed.inject(UploadService);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => httpTesting.verify());
it('maps progress events to percentages', () => {
const states: UploadState[] = [];
const file = new File(['hello'], 'hello.txt');
service.upload(file).subscribe(s => states.push(s));
const req = httpTesting.expectOne('/api/files');
expect(req.request.reportProgress).toBe(true);
req.event({ type: HttpEventType.UploadProgress, loaded: 50, total: 200 });
req.event({ type: HttpEventType.UploadProgress, loaded: 80 });
req.flush({ id: 'f1', url: '/files/f1' });
expect(states).toEqual([
{ kind: 'progress', loaded: 50, percent: 25 },
{ kind: 'progress', loaded: 80, percent: null },
{ kind: 'done', result: { id: 'f1', url: '/files/f1' } }
]);
});
});The testing backend doesn't emit a Sent event, so the expected list starts with the first progress state. The second progress event leaves out total on purpose. It checks that the service handles an unknown size instead of producing NaN.
Exercise
A teammate writes http.post<UploadResult>(url, formData, { reportProgress: true }) and subscribes, but no progress events ever arrive. The app does not use withFetch(). What is wrong, and what is the fix?
Show answer
Without observe: 'events', HttpClient emits only the response body, and the progress events are discarded. Add observe: 'events' so the Observable's type becomes Observable<HttpEvent<UploadResult>>. Then check event.type === HttpEventType.UploadProgress to read loaded and total.
Exercise
A download progress bar shows "NaN%" for one API endpoint but works for others. What is the likely cause, and how should the code handle it?
Show answer
That endpoint doesn't send a Content-Length header, for example because it streams with chunked transfer encoding, so event.total is undefined. Compute the percentage only when total is truthy. Otherwise show an indeterminate indicator or the number of bytes received (loaded).
Exercise
The app uses provideHttpClient(withFetch(), withInterceptors([logInterceptor])). Upload progress never fires, and the final response body also comes through as undefined. Name the two separate causes.
Show answer
First, the fetch backend has no upload progress hook, so it never emits UploadProgress events. Second, logInterceptor probably treats every event as an HttpResponse and maps it to its body, which breaks the event stream. The interceptor must pass non-Response events through unchanged.