How To Preview Image Before Submitting Form In JavaScript

admin_img Posted By Bajarangi soft , Posted On 06-10-2020

In Java script we can preview image before data submitting so today we discuss how to preview image before uploading using java script

How To Preview Image Before Submitting Form In JavaScript

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

<form >
    <input type='file' class="form-control"/>
    <br><img id="myImg" src="../image/demo5.jpg" alt="your image" height=300 width=500>
    <br><br><input type="submit" class="btn btn-success" value="submit"/>
</form>

Step 2: Now implement java script to preview image 
window.addEventListener('load', function() {
    document.querySelector('input[type="file"]').addEventListener('change', function() {
        if (this.files && this.files[0]) {
            var img = document.querySelector('img');  // $('img')[0]
            img.src = URL.createObjectURL(this.files[0]); // set src to blob url
            img.onload = imageIsLoaded;
        }
    });
});

function imageIsLoaded() {
    alert(this.src);  // blob url
    // update width and height ...
}
 

Complete Code For Previewing Image Before Submitting Form In JavaScript

<!DOCTYPE html>
<html>
<head>
    <title>How To Preview Image Before Submitting Form In JavaScript</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>

</style>
<body>
<div class="container">
    <br>
    <div class="text-center">
        <h1 style="color: tomato">How To Preview Image Before Submitting Form In JavaScript</h1>
    </div>
    <div class="well">
        <form>
            <input type='file' class="form-control"/>
            <br><img id="myImg" src="../image/demo5.jpg" alt="your image" height=300 width=500>
            <br><br><input type="submit" class="btn btn-success" value="submit"/>
        </form>
    </div>
    <script>
        window.addEventListener('load', function () {
            document.querySelector('input[type="file"]').addEventListener('change', function () {
                if (this.files && this.files[0]) {
                    var img = document.querySelector('img');  // $('img')[0]
                    img.src = URL.createObjectURL(this.files[0]); // set src to blob url
                    img.onload = imageIsLoaded;
                }
            });
        });

        function imageIsLoaded() {
            alert(this.src);  // blob url
            // update width and height ...
        }
    </script>
</div>
</body>
</html>

 

Related Post