Published Jul 22,2019 by Kailash Singh
Image preview before upload with javascript & jquery

In this tutorial, we are creating a Image preview before upload with JavaScript & JQuery.

 

This post portrays you how to see a picture on before transferring to the server by utilizing javascript bit by bit. utilizing FileReader and jquery. 

 

Picture see is significant capacity while customer transfer picture. some time customer what to comprehend what picture transferring.

 

Step 1:- Add Link in page

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

 

Step 2:- Add HTML Code.

 

<img id="preview" src="https://i.imgur.com/bgouN5M.jpg" width="350px" height="320px"/><br/>
<input type="file" id="image" style="display: none;"/>
<a href="javascript:changeProfile()">Change</a> |
<a style="color: red" href="javascript:removeImage()">Remove</a>

 

Step 3:- Add JavaScript & Jquery Code.

 

<script>

    function changeProfile() {
        $('#image').click();
    }

    $('#image').change(function () {
        var imgPath = this.value;
        var ext = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
        if (ext == "png" || ext == "jpeg" || ext == "gif" || ext == "jpg")
            readURL(this);
        else
            alert("Please select image file ( png, jpeg,  jpg).")
    });

    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.readAsDataURL(input.files[0]);
            reader.onload = function (e) {
                $('#preview').attr('src', e.target.result);
            };
        }
    }

    function removeImage() {
        $('#preview').attr('src', 'noimage.jpg');
    }

</script>

 

Hope this will help our developers.

Because we believe Mantra means CodingMantra

1 Comment

Prabhat Singh said:

Thanks alot. It's Working

  • Oct 23, 2019

Leave a Reply