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>
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>