Preview an image before uploading using jQuery

Preview an image before uploading using jQuery

08-Nov-2023
| |
Image Carousel

Table of Contents

S.no Contents-topics
1 Introduction
2 HTML code

1:Introduction

Preview an image before uploading using jQuery we are going to use the JavaScript constructor FileReader() to read the image provided and then we shall display it. We have used img tag to display the image we get from the file we upload. Then we used FileReader() to get the file and then we used reader.readAsDataURL(file) to read the file as it is a image file or not.

2:HTML code

HTML code Copy

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <title>Preview an image using jQuery</title>
    </head>
    <body>
        <span class="heading">Developer Corner Preview an image before uploading using jQuery</span>
        <form>
            <div class="holder">
                <img id="imgPreview" src="#" alt="pic" />
            </div>
            <input type="file" name="photograph"
                id="photo" required="true" />
        </form>
        <style>
            .holder {
                height: 300px;
                width: 300px;
                border: 2px solid black;
            }
            img {
                max-width: 300px;
                max-height: 300px;
                min-width: 300px;
                min-height: 300px;
            }
            input[type="file"] {
                margin-top: 5px;
            }
            .heading {
                font-family: Montserrat;
                font-size: 45px;
                color: green;
            }
        </style>
        <script>
            $(document).ready(() => {
                $("#photo").change(function () {
                    const file = this.files[0];
                    if (file) {
                        let reader = new FileReader();
                        reader.onload = function (event) {
                            $("#imgPreview")
                            .attr("src", event.target.result);
                        };
                        reader.readAsDataURL(file);
                    }
                });
            });
        </script>
    </body>
</html>

Output of Preview an image before uploading:

pic

 

Tags: preview of an image before uploading using jQuery , preview of an image using jquery , how to show image using jquery,jquery , advance jquery , jquery advance code,
0 Comments (Please let us know your query)
Leave Comment
Leave Comment
Articles from other Categories
Load More

Newsletter