How To Preview Image Before Uploading Using Javascript

admin_img Posted By Bajarangi soft , Posted On 15-01-2021

Learn how to preview image before upload using javascript

image-preview-javascript

Step 1:Create index.html and implement below html code in it.

<div class="container">
    <div class="col-md-12 bs_card mt-3">
        <h1>Image Preview In Javascript</h1>
        <div class="col-md-6 mt-3">
            <div class="form-group">
                <input type="file" class="form-control" id="logo_img" name="logo_img">
            </div>
            <div class="clearfix"></div>
            <img class="" src="" id="preview_img">
        </div>
    </div>
</div>

Step 2:Add script for onchange function to preview image
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#preview_img').attr('src', e.target.result);
            $('#preview_img').addClass('img_logo');
        };
        reader.readAsDataURL(input.files[0]);
    }
}
$("#logo_img").change(function(){
    readURL(this);
});

Complete Code For Image Preview Using Javascript
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Image Preview</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
    <style>
        .img_logo{
            width: 100px;
            height: 100px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="col-md-12 bs_card mt-3">
        <h1>Image Preview In Javascript</h1>
        <div class="col-md-6 mt-3">
            <div class="form-group">
                <input type="file" class="form-control" id="logo_img" name="logo_img">
            </div>
            <div class="clearfix"></div>
            <img class="" src="" id="preview_img">
        </div>
    </div>
</div>

<script>
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#preview_img').attr('src', e.target.result);
                $('#preview_img').addClass('img_logo');
            };
            reader.readAsDataURL(input.files[0]);
        }
    }
    $("#logo_img").change(function(){
        readURL(this);
    });
</script>
</body>
</html>

Related Post