ImagePreview Example -- Source Code

HTML Page -- index.htm

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Client-Side File Display</title>
        <link rel="stylesheet" href="styles.css">
        <script src="script.js"></script>
    </head>
    <body>
        <h1>Select a File to Preview</h1>
        <!-- accept attribute restricts file types to 
             images for this example -->
        <input type="file" id="fileInput" accept="image/*"><br><br>

        <!-- Display image preview here. -->
        <img id="imagePreview" src="#" alt="Image Preview">
    </body>
</html

CSS Page -- styles.css

/* CSS file for FilePreview Example 
   Source code file: styles.css      */

/* Set font and background color for body */
body { font: 120% arial, sans-serif; 
       background-color: #F0F0FF; }

/* Set properties for image preview element.*/
img { max-width: 300px; max-height: 300px; 
      display: none; }

Script Page -- script.js

// Source code file: script.js
// Define variables global objects that 
// can be accessed anywhere.
var fileInput = null;
var imagePreview = null;

function handleFileSelection(event) {

    // Get first file from FileList object.
    var file = event.target.files[0]; 

    // If file is not null, process file.
    if (file) {
        // Clear previous previews
        imagePreview.style.display = 'none';
        imagePreview.src = '#';

        // Create a new FileReader object
        const reader = new FileReader();

        // Check if the file is an image or text
        if (file.type.startsWith('image/')) {
            // Use readAsDataURL for images to create 
            // a data string to display.
            reader.readAsDataURL(file); 
            reader.addEventListener("load", ( ) => {
                imagePreview.src = reader.result;
                imagePreview.style.display = "block";
            });
        } else {
            alert("Unsupported file type. Select an image.");
        }

        // Handle potential errors during file reading
        reader.onerror = () => {
            console.error("Error reading the file:", 
                reader.error);
            alert("Error reading the file.");
        };
    }
}

function init( ) {
    // Create object for fileInput element and 
    // add an event listener to detect when a file 
    // is selected.
    fileInput = document.getElementById("fileInput");
    fileInput.addEventListener("change", handleFileSelection);

    // Create object for imagePreview element.
    imagePreview = document.getElementById("imagePreview");
    
}

// Run init method when DOM tree has been created.
document.addEventListener("DOMContentLoaded", init);