Previewing Image Before File Upload – JavaScript Tutorial




In this video I’ll be demonstrating how it’s possible to use some simple JavaScript in order to display a preview of an image before uploading it to the web server.

Support me on Patreon:
https://www.patreon.com/dcode – with enough funding I plan to develop a website of some sort with a new developer experience!

Follow me on Twitter @dcodeyt!

If this video helped you out and you’d like to see more, make sure to leave a like and subscribe to dcode!

Original source


21 responses to “Previewing Image Before File Upload – JavaScript Tutorial”

  1. <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!– Compiled and minified CSS –>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"&gt;
    <!– Compiled and minified JavaScript –>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script&gt;
    <!–Import Google Icon Font–>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <style>
    .image-preview
    {
    width: 150px;
    min-height: 150px;
    border: 2px solid #dddddd;
    margin-top: 15px;

    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    color: 11#cccccc;
    }
    .image-preview__image
    {
    display: none;
    width: 100%;
    }

    </style>
    <title>Document</title>
    </head>
    <body>

    <input type="file" name="inpFile" id="inpFile">
    <div class="image-preview" id="imagePreview">
    <div class="card-image">
    <img src="" alt="Image Preview" class="image-preview__image">
    </div>
    <img src="" alt="Image Preview" class="image-preview__image">
    <span class="image-preview__default-text">Image</span>
    </div>

    <script>
    const inpFile = document.getElementById("inpFile");
    const previewContainer = document.getElementById("imagePreview");
    const previewImage = previewContainer.querySelector(".image-preview__image");
    const previewDefaultText = previewContainer.querySelector(".image-preview__default-text");

    inpFile.addEventListener("change", function() {
    const file = this.files[0];

    if (file) {
    const reader = new FileReader();

    previewDefaultText.style.display = "none";
    previewImage.style.display = "block";

    reader.addEventListener("load", function() {
    previewImage.setAttribute("src", this.result);

    });

    reader.readAsDataURL(file);

    }else{
    previewDefaultText.style.display=null;
    previewImage.style.display=null;
    previewImage.setAttribute("src", "");
    }

    });
    </script>
    </body>

    </html>

Leave a Reply