Preview image before uploading

On some of the HTML forms, users should add a picture or an image. In such a case, it is handy to display a preview of the image – just in case. One of the simple methods to achieve this is such a code:

<form>
    <input type="file" id="newImage" name="newImage" accept="image/png,image/jpeg" />
    <div id="newImagePlaceholder" >
        <img id="newImagePreview" src="##" alt="Your new image preview" style="display: none">
    </div>
</form>

<script>
    let imgReader = new FileReader();
	
    imgReader.onload = function (e) {
        let thisImage = document.getElementById('newImagePreview');
        thisImage.src = e.target.result;
    }

    function readURL(input) {
        if (input.files && input.files[0]) {
            imgReader.readAsDataURL(input.files[0]);
        }
    }
    
    document.getElementById('newImage').onchange = function(){
        document.getElementById('newImagePreview').style.display = '';
        readURL(this);
    };
</script>

There is an event handler created on the change of the New Image field. Once the image is selected, it is loaded from the disk to the image element on the website. Please note that the file is not yet sent to the server. The whole process takes place in the browser.

Of course, you should pay attention to the styling of the preview image element. You never know how big is the image is being uploaded, or what shape it is. In most cases, I’m simply adjusting the maximum width and height to make sure that the page design is not broken.

Leave a Reply

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