Using JavaScript to Preview an Image Upload

If you’ve read my last two posts (most recent one here), you now know a way to upload and retrieve an image to/from a mySQL database. The examples provided, however, are pretty barebones. There are a lot of quality-of-life features that can be added to a form like this – one of which is displaying a preview of the image before it gets uploaded.

Luckily, this can be accomplished with a few lines of JS!

First, we’re going to need an image tag in our html, like so:

<img class="coverImage" name="uploadedCover" id="uploadedCover" width="300px;" src="#" />

(Note that, as-is, this will display a broken image thumbnail until a file is selected. I’ve not yet done this in my personal project, but if anyone has a suggestion on how to efficiently hide the image until a file is chosen feel free to comment below!)

Next, we’re going to need our input, which you should already have if you’ve been following along. Note the onchange JS function of readImage – that’s our next step.

<input type="file" name="cover" id="cover" accept=".png" onchange="readImage(this)">

Now that we’ve set up the necessary elements in our html/php, we’re going to hop over to our JavaScript page (this could also be done in a <script> block):

function readImage(input) {
    if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                    $('#uploadedCover')
                        .attr('src', e.target.result)
                        .width(300)
            };

            reader.readAsDataURL(input.files[0]);
        }
}

This makes use of JavaScript’s file reading functionality to set the src attribute of the uploadedCover image tag to our chosen image.

That done, you should have a working image upload with a preview feature!

Next up, we’ll be switching gears and heading over to CSS-land with how to make a dark/light mode theme switcher (using CSS variables and JavaScript).

Leave a Reply

Your email address will not be published. Required fields are marked *