Skip to main content

JavaScript
Preview Image(s) Before Upload

script.js

// AZUL CODING ---------------------------------------
// JavaScript - Preview Image(s) Before Upload
// https://youtu.be/KCPqGhLiCH8


const fileInput = document.getElementById("file-input");
const container = document.getElementById("container");

function loadFile() {
    container.innerHTML += 
        `<img src="${this.result}" width="180"/>`;
}

function addSingleFile() {
    container.innerHTML = "";

    let reader = new FileReader();
    reader.addEventListener("load", loadFile);
    reader.readAsDataURL(this.files[0]);
}

function addMultipleFiles() {
    container.innerHTML = "";

    for (const file of this.files) {
        let reader = new FileReader();
        reader.addEventListener("load", loadFile);
        reader.readAsDataURL(file);
    }
}

document.addEventListener("DOMContentLoaded", () => {
    fileInput.addEventListener("change", addMultipleFiles);

    // Replace with line below to restrict to single file
    // fileInput.addEventListener("change", addSingleFile);
});

Enjoying this tutorial?


index.html

<!-- AZUL CODING --------------------------------------- -->
<!-- JavaScript - Preview Image(s) Before Upload -->
<!-- https://youtu.be/KCPqGhLiCH8 -->


<!DOCTYPE html>
<html>
    <head>
        <title>Azul Coding</title>
        <style>
            body {
                margin: 30px;
                background-color: #03506E;
                color: white;
                font-size: 18px;
            }
            * {
                font-family: sans-serif;
            }
            #container {
                display: flex;
                flex-wrap: wrap;
                gap: 10px;
            }
            input[type=file] {
                display: block;
                margin-top: 10px;
                margin-bottom: 30px;
                border: 2px solid #49C8FC;
                padding: 5px;
            }
        </style>
        <script defer src="script.js"></script>
    </head>
    <body>
        <label for="file-input">Select files:</label>
        <input id="file-input" type="file" multiple>
        <!-- Remove the multiple attribute to restrict to a single file -->

        <div id="container"></div>
    </body>
</html>