Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Preview a selected image in Angular by handling the file input’s change event, keeping the chosen File, and assigning URL.createObjectURL(file) to an image element. Revoke that object URL when the preview is replaced, cleared, or the component is destroyed. The preview is local browser work; upload the original file separately when the user submits the form.

Minimal Angular preview

This standalone pattern works with a template-driven or otherwise ordinary Angular component. The accept attribute narrows the picker to images, but it is only a user-interface hint. Your component must still validate the selected file.

Template

<input
  type="file"
  accept="image/*"
  (change)="onImageSelected($event)"
>

<p *ngIf="validationError" role="alert">
  {{ validationError }}
</p>

<img
  *ngIf="previewUrl"
  [src]="previewUrl"
  alt="Selected image preview"
>

<button type="button" (click)="clearPreview()" [disabled]="!previewUrl">
  Clear
</button>

<button type="button" (click)="upload()" [disabled]="!selectedFile">
  Upload
</button>

Component code

import { Component, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-image-picker',
  templateUrl: './image-picker.component.html'
})
export class ImagePickerComponent implements OnDestroy {
  previewUrl: string | null = null;
  selectedFile: File | null = null;
  validationError = '';

  onImageSelected(event: Event): void {
    const input = event.target as HTMLInputElement;
    const file = input.files?.[0] ?? null;

    this.clearPreview();
    this.validationError = '';

    if (!file) {
      return;
    }

    if (!file.type.startsWith('image/')) {
      this.validationError = 'Choose an image file.';
      return;
    }

    this.selectedFile = file;
    this.previewUrl = URL.createObjectURL(file);
  }

  clearPreview(): void {
    if (this.previewUrl) {
      URL.revokeObjectURL(this.previewUrl);
    }

    this.previewUrl = null;
    this.selectedFile = null;
  }

  upload(): void {
    if (!this.selectedFile) {
      return;
    }

    // Send this.selectedFile with your application’s upload request.
  }

  ngOnDestroy(): void {
    this.clearPreview();
  }
}

URL.createObjectURL() returns a temporary URL representing the selected file. Angular binds it to src, while selectedFile remains available for the eventual upload. Do not revoke the URL immediately after assigning it: the image still needs it. Revoke it when it is no longer displayed.

What happens when the user selects a file

  1. The browser fires change on the file input.
  2. The handler reads the first entry from input.files. A web page can access files the user selected (or dropped), not arbitrary paths on the user’s computer.
  3. The component checks the file’s type and any application-specific limits.
  4. An object URL is generated and stored in component state.
  5. Angular updates the image’s src, so the browser renders the local file without a network upload.
  6. When the selection changes, the old URL is revoked before the new one is stored.

Previewing does not send data to your server. Keep the File object and perform an explicit upload, commonly with FormData, when the user confirms.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Validation that belongs in a real component

Type and extension

accept="image/*" improves the picker experience, but it does not establish that a file is safe or acceptable. Check file.type, and if your policy allows only particular formats, use an explicit allow-list such as image/png, image/jpeg, or image/webp. File names and extensions are user-controlled.

Size limits

Reject files above the limit your application can process before creating a preview. For example:

const maxBytes = 5 * 1024 * 1024; // 5 MiB
if (file.size > maxBytes) {
  this.validationError = 'The image must be 5 MiB or smaller.';
  return;
}

Choose a limit that matches your server and image-processing pipeline; the number above is only an example.

Dimensions

If your UI requires a minimum or maximum width and height, inspect the object URL with an Image before accepting it:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
private validateDimensions(file: File, url: string): Promise<void> {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.onload = () => {
      if (image.width < 400 || image.height < 300) {
        reject(new Error('Image must be at least 400 × 300 pixels.'));
      } else {
        resolve();
      }
    };
    image.onerror = () => reject(new Error('The image could not be decoded.'));
    image.src = url;
  });
}

Whichever checks you add in the browser, repeat authoritative validation on the server. Client-side validation is feedback, not a security boundary.

Replacing and clearing previews safely

Every generated object URL should have a matching URL.revokeObjectURL(). The example’s clearPreview() handles both replacement and manual clearing, and ngOnDestroy() covers navigation away from the component. Clearing selectedFile prevents an old file from being uploaded after its preview has disappeared.

If you reset the native input, also clear its value so selecting the same file again fires change:

clearInput(input: HTMLInputElement): void {
  this.clearPreview();
  input.value = '';
}

Call this method from a clear button by passing a template reference, or use @ViewChild if that better fits your form.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Object URL or FileReader?

Approach Result Best fit Cleanup
URL.createObjectURL(file) A temporary URL referring to the selected File A straightforward, display-only preview Revoke when replaced, removed, or destroyed
FileReader.readAsDataURL(file) An asynchronously produced data: URL containing encoded file data Code that specifically needs a data URL string Discard the reader result when the preview is replaced; there is no object URL to revoke

FileReader example

onImageSelectedWithReader(event: Event): void {
  const input = event.target as HTMLInputElement;
  const file = input.files?.[0] ?? null;
  this.clearPreview();

  if (!file || !file.type.startsWith('image/')) {
    this.validationError = 'Choose an image file.';
    return;
  }

  this.selectedFile = file;
  const reader = new FileReader();
  reader.addEventListener('load', () => {
    this.previewUrl = typeof reader.result === 'string'
      ? reader.result
      : null;
  });
  reader.addEventListener('error', () => {
    this.validationError = 'The image could not be read.';
    this.selectedFile = null;
  });
  reader.readAsDataURL(file);
}

A data URL can be convenient when another API explicitly requires one, but it represents the file as encoded text. For simply setting an image source, an object URL is the more direct choice.

Multiple-image previews

Use multiple, iterate through all selected files, and associate each URL with its file. Revoke the individual URL when a thumbnail is removed and all remaining URLs when the component is destroyed.

previews: Array<{ file: File; url: string }> = [];

onImagesSelected(event: Event): void {
  const input = event.target as HTMLInputElement;
  this.clearAllPreviews();

  for (const file of Array.from(input.files ?? [])) {
    if (file.type.startsWith('image/')) {
      this.previews.push({ file, url: URL.createObjectURL(file) });
    }
  }
}

removePreview(index: number): void {
  const [removed] = this.previews.splice(index, 1);
  if (removed) URL.revokeObjectURL(removed.url);
}

clearAllPreviews(): void {
  for (const preview of this.previews) {
    URL.revokeObjectURL(preview.url);
  }
  this.previews = [];
}

ngOnDestroy(): void {
  this.clearAllPreviews();
}

Uploading after the preview

Keep upload logic separate so a user can inspect, replace, or cancel a selection. A typical Angular service call sends the original file:

const form = new FormData();
form.append('image', this.selectedFile, this.selectedFile.name);

this.http.post('/api/images', form).subscribe({
  next: () => this.clearPreview(),
  error: () => this.validationError = 'Upload failed. Try again.'
});

Do not manually set the multipart Content-Type header when using FormData; the browser supplies the boundary. Your server should verify the decoded content, size, dimensions, and authorization independently of browser checks.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting

The preview is blank

  • Confirm that previewUrl is assigned and that the template uses [src]="previewUrl", not an interpolated literal with a stale value.
  • Check that the selected file is an image and that the browser can decode it.
  • Make sure you did not call URL.revokeObjectURL() immediately after assigning the URL.

Selecting the same file does nothing

File inputs may not emit change when their value has not changed. Set the input’s value to an empty string after clearing, as shown above.

The old image remains after choosing a new one

Clear the previous URL and file at the start of the handler. Do not append a new preview without removing the old state.

Memory usage grows after many selections

Each object URL holds a reference until revoked. Revoke on replacement, removal, and component destruction; for multiple files, track and revoke every URL.

A valid-looking file is rejected

Some browsers provide an empty or unexpected MIME type. If your product permits that case, combine a cautious extension check with server-side content verification rather than trusting either value alone.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

The upload still succeeds after clearing

Clear both previewUrl and selectedFile. The image element disappearing does not automatically remove the file stored in component state.

Or skip the browser setup

If you need a screenshot of a web page rather than a local upload preview, ScreenshotNeo provides a single HTTP request that returns PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for all options. A direct cURL call is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is included on every plan, and yearly billing provides two months free. Create a free ScreenshotNeo account to begin.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can Angular preview an image without uploading it?

Yes. A user-selected File can be rendered locally with an object URL or a FileReader data URL; no request is made until your upload code sends the File.

Should I store the preview URL in a database?

No. An object URL is local, temporary browser state. Store the uploaded asset’s server URL only after your server accepts and stores the file.

Why does the file input expose a File object instead of a local path?

Browser security intentionally gives scripts the user-authorized File data while withholding unrestricted access to arbitrary local filesystem paths.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.