← Back to Angular, page 10

angular-0194 · Hard senior

Build a file upload with progress, cancel and client-side validation using HttpClient. How do you report progress, and what must still be checked on the server?

Send FormData with reportProgress and observe events. Map UploadProgress events to a percentage and the final Response event to done. Cancel by unsubscribing (which aborts the request). Check size and type on the client for quick feedback, but always validate again on the server.

Full answer

Uploads need three things that normal GET and POST calls do not: progress, cancel and validation.

Progress. Use http.post(url, formData, { reportProgress: true, observe: 'events' }). The observable emits HttpEvent objects:

  • HttpEventType.Sent: the request left.
  • HttpEventType.UploadProgress: has loaded and total (bytes). The percentage is Math.round(100 * loaded / total). total can be undefined when the size is unknown.
  • HttpEventType.ResponseHeader and DownloadProgress: for the response.
  • HttpEventType.Response: the final body. Treat this as success.

Backend note: the Fetch API cannot report upload progress, and the XHR API can. In Angular 20 the XHR backend is the default, so reportProgress: true works, and adding withFetch() removes upload progress. In the newest Angular documentation, fetch is the default backend and withFetch() is deprecated. There you configure provideHttpClient(withXhr()) for uploads that need progress, and use the options reportUploadProgress and reportDownloadProgress (the single reportProgress option is deprecated, and reportUploadProgress with the fetch backend throws an error). Check which backend your version uses.

Cancel. Unsubscribing from the observable aborts the request (xhr.abort()). Put it behind takeUntil(cancel$) or keep the Subscription and call unsubscribe() from a Cancel button. Reset the progress state afterwards. In a component, add takeUntilDestroyed() too, so leaving the page cancels the upload.

Client-side validation (fast feedback, not security): check file.size against a limit, check file.type or the extension against an allowlist, and check the count. Show clear messages. Use accept=".pdf,.png" on the input as a hint only, because users can bypass it.

Server-side validation (the real protection): size limit at the proxy and in the app, content type detection by reading the file (not trusting the name or MIME type sent by the client), virus scanning, a safe storage name (never use the client file name as a path), authentication and authorization, and rate limits. For large files consider chunked or resumable uploads (tus protocol) and direct upload to object storage with a signed URL, which also avoids loading the file through your server.

UI details: disable the button while uploading, announce progress to screen readers (<progress> element with value and max, or aria-live text), and show errors with a retry option.

Test with HttpTestingController: req.event({ type: HttpEventType.UploadProgress, loaded: 50, total: 100 }) simulates progress, and flush completes the request.

typescript
import { HttpClient, HttpEvent, HttpEventType } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, filter, map } from 'rxjs';

export type UploadState = { kind: 'progress'; percent: number } | { kind: 'done'; body: unknown };

const MAX_BYTES = 5 * 1024 * 1024;
const ALLOWED = ['application/pdf', 'image/png'];

export function validateFile(file: { size: number; type: string }): string | null {
  if (file.size > MAX_BYTES) return 'File is larger than 5 MB';
  if (!ALLOWED.includes(file.type)) return 'Only PDF and PNG files are allowed';
  return null; // the server must still check
}

@Injectable({ providedIn: 'root' })
export class UploadService {
  private readonly http = inject(HttpClient);

  upload(file: File): Observable<UploadState> {
    const body = new FormData();
    body.append('file', file, file.name);
    // Angular 20: reportProgress. Newer versions: reportUploadProgress: true (with withXhr()).
    return this.http.post('/api/upload', body, { reportProgress: true, observe: 'events' }).pipe(
      map((event: HttpEvent<unknown>): UploadState | null => {
        if (event.type === HttpEventType.UploadProgress) {
          return { kind: 'progress', percent: event.total ? Math.round((100 * event.loaded) / event.total) : 0 };
        }
        return event.type === HttpEventType.Response ? { kind: 'done', body: event.body } : null;
      }),
      filter((state): state is UploadState => state !== null),
    );
  }
}

Angular 20.3, type-checked with ngc. No Karma test was run for this item. The backend limitation (fetch has no upload progress; use the XHR backend) comes from the Angular HttpClient documentation on angular.dev, checked in December 2026, and was not tested here. The snippet uses `reportProgress`, which is the option in Angular 20.3. The current docs use `reportUploadProgress` and `reportDownloadProgress` with `provideHttpClient(withXhr())`. Those APIs are not in the installed 20.3.

Key points

  • Use `reportProgress: true` with `observe: 'events'`. `UploadProgress` gives `loaded` and `total`.
  • Unsubscribing aborts the request. Use it for cancel and for leaving the page.
  • Client checks give quick feedback. Server checks are the real validation.
  • The fetch backend has no upload progress. Use the XHR backend (the default in Angular 20, or `withXhr()` in newer versions) for uploads that need progress.

Common mistakes

  • Trusting `accept` or the file extension as validation.
  • Using the fetch backend and expecting upload progress.
  • Using the client file name as a storage path on the server.

Follow-ups

  • How would you resume an interrupted large upload?
  • Why upload directly to object storage with a signed URL?
  • How do you make the progress accessible?

Tips

  • List the event types you use.
  • Separate client convenience checks from server security checks.
  • Mention cancel through unsubscribe.

Evaluation rubric

  • Implements progress and completion mapping correctly.
  • Cancels cleanly and validates on both sides.
  • Knows the fetch backend limitation.