Preview an image before uploading using jQuery

Preview an image before uploading using jQuery

24-Sep-2022
| |
Image Carousel

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.

Code for Preview an image before uploading using jQuery 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: Image, jQuery,jquery , advance jquery , jquery advance code,
Related Articles
Load More

Newsletter