Image preview before upload with javascript & jquery step by step

Generic placeholder image
Brijpal Sharma
html javascript  

Date:-June 03rd, 2019 , Posted On:- Web Development


This post describes you how to preview an image on before uploading to the server by using javascript step by step. using FileReader and jquery.

Image preview before upload with javascript & jquery step by step

Image preview is very important function while client upload image. some time client what to know what image uploading.

<!DOCTYPE html>
<html>
<head>
    <title>Image Preview</title>
</head>
<body style="background: lightgrey">
<center>
    <br/><br/><br/>
    <img id="preview" src="https://i.imgur.com/bgouN5M.jpg" width="350px" height="320px"/><br/>
    <input type="file" id="image" style="display: none;"/>
    <!--<input type="hidden" style="display: none" value="0" name="remove" id="remove">-->
    <a href="javascript:changeProfile()">Change</a> |
    <a style="color: red" href="javascript:removeImage()">Remove</a>
</center>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    function changeProfile() {
        $('#image').click();
    }
    $('#image').change(function () {
        var imgPath = this.value;
        var ext = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
        if (ext == "gif" || ext == "png" || ext == "jpg" || ext == "jpeg")
            readURL(this);
        else
            alert("Please select image file (jpg, jpeg, png).")
    });
    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);
//              $("#remove").val(0);
            };
        }
    }
    function removeImage() {
        $('#preview').attr('src', 'noimage.jpg');
//      $("#remove").val(1);
    }
</script>
</body>
</html>

So here we completed the tutorial on Image preview before upload with javascript & jquery step by step hope it's will help.


About the author

user profile
Brijpal Sharma

Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...

0 comments

You must be logged in to post a comment.