How to make a preview of the image, what would it be displayed in a specific div before uploading to the server? I tried this option, it does not work

<form name="" method="post" action="#" enctype="multipart/form-data" class="feedback-form-1"> <fieldset> <div class="input-file-row-1"> <div class="upload-file-container"> <img id="image" src="#" alt="" /> <div class="upload-file-container-text"> <span>Add<br />photo</span> <input type="file" name="pic[]" class="photo" id="imgInput" /> </div> </div> </div> </fieldset> </form> 

Js code

 function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#image').attr('src', e.target.result); }; reader.readAsDataURL(input.files[0]); } } $("#imgInput").change(function(){ readURL(this); }); 
  • And what's the problem then? - Tsyklop

1 answer 1

I am wondering: you do not have jQuery library loaded.

Try it - this is your code:

 function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#image').attr('src', e.target.result); }; reader.readAsDataURL(input.files[0]); } } $("#imgInput").change(function(){ readURL(this); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="" method="post" action="#" enctype="multipart/form-data" class="feedback-form-1"> <fieldset> <div class="input-file-row-1"> <div class="upload-file-container"> <img id="image" src="#" alt="" /> <div class="upload-file-container-text"> <span>Add<br />photo</span> <input type="file" name="pic[]" class="photo" id="imgInput" /> </div> </div> </div> </fieldset> </form>