• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Image Effects / Preview an image before uploading it

Preview an image before uploading it

Preview an image before uploading it

We prepare the markup for a file input which allows to choose an image, and an img element for previewing the selected file.

<input type="file" id="fileInput" />

<img id="preview" />

Both elements can be taken by the getElementById() method:

const fileEle = document.getElementById('fileInput');
const previewEle = document.getElementById('preview');

1. Use the URL.createObjectURL() method

fileEle.addEventListener('change', function (e) {
    // Get the selected file
    const file = e.target.files[0];

    // Create a new URL that references to the file
    const url = URL.createObjectURL(file);

    // Set the source for preview element
    previewEle.src = url;
});

2. Use the FileReader’s readAsDataURL() method

fileEle.addEventListener('change', function (e) {
    // Get the selected file
    const file = e.target.files[0];

    const reader = new FileReader();
    reader.addEventListener('load', function () {
        // Set the source for preview element
        previewEle.src = reader.result;
    });

    reader.readAsDataURL(file);
});

Source

https://htmldom.dev/preview-an-image-before-uploading-it/

Image Effects

Related Snippets:

  • Zoom an image
  • Create an image comparison slider
  • Next-Previous Image Gallery
  • How To Preview an Image Before it is Uploaded (Using JavaScript)

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers