Image preview show after image upload using jQuery.

In this small tutorial, I will teach you how to get the preview of the image after uploading.

In this step, we have to create an HTML file name is image.html and put the below code.


Image:<br>
<input name="files" type="file" id="post_image">
<img src="" id="post_img_show" width="200px" />
<br><br>

After creating an HTML file you have put the below jQuery code in your file

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#post_img_show').attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
        $("#post_image").change(function(){
            readURL(this);
        });
</script>

Here’s the final code:

Image:<br>
<input name="files" type="file" id="post_image">
<br>
<br>
<img src="" id="post_img_show" width="700px" height="500px" />
<br><br>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#post_img_show').attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
        $("#post_image").change(function(){
            readURL(this);
        });
</script>

Output:



Now Open your browser an run this URL:

http://localhost/image.html

About Dhaval Shah

My name is Dhaval Shah. I'm a Laravel developer. I live in India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Java-script, JQuery, Laravel, WordPress, and Bootstrap.
Follow me on Github / Linkedin

4 Comments

  1. I’m not really sure why you’re using JQuery as you’re using very little of it and could easly be done with a standard event listener. Just adding bloat to the code.

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!