Open In App

Preview an image before uploading using jQuery

Last Updated : 18 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to discuss how we can preview an image before uploading it using jQuery. There are two different ways of achieving this task as listed below:

Using the FileReader() constructor function

The FileReader() constructor function can be used to get the URL of the uploaded image that can be later replaced or assigned to the src of the img tag on the web page to show preview.

Syntax:

const reader = new FileReader();
reader.onload(()=>{});

Example: The below example explains the practical use of the FileReader constructor to preview the uploaded image.

html




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
          content=
"width=device-width, initial-scale=1.0" />
    <title>Geeks</title>
 
    <script src=
            integrity=
"sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
            crossorigin="anonymous"
            referrerpolicy="no-referrer">
    </script>
 
    <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>
</head>
 
<body>
    <center>
        <span class="heading">Geeks For Geeks</span>
        <form id="myForm">
            <div class="holder">
                <img
                    id="imgPreview"
                    src="#" alt="pic" />
            </div>
            <input
                type="file"
                name="photograph"
                id="photo"
                required="true" />
            <input type="button"
                   id="formBtn"
                   value="Upload Image">
        </form>
    </center>
    <script>
        $(document).ready(() => {
            const photoInp = $("#photo");
            let file;
 
            $('#formBtn').click((e)=>{
                e.preventDefault();
                if(file){
                    alert("The image is uploaded successfully!!");
                }
                else{
                    alert("Please select a Image first!!");
                }
                 
            });
 
            photoInp.change(function (e) {
                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: 

prevImageGIF

Using the createObjectURL() method

The createObjectURL() method can also be used to create the dynamic URL of the image that is selected using the input type file and then change the src of the img to the dynamically created URL.

Syntax:

const imgURL = URL.createObjectURL(selected_file);

Example: The below example will explain the use of the createObjectURL() method to preview the image before upload.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
          content=
"width=device-width, initial-scale=1.0" />
    <title>Geeks</title>
 
    <script src=
            integrity=
"sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
            crossorigin="anonymous"
            referrerpolicy="no-referrer">
    </script>
 
    <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>
</head>
 
<body>
    <center>
        <span class="heading">Geeks For Geeks</span>
        <form id="myForm">
            <div class="holder">
                <img
                    id="imgPreview"
                    src="#" alt="pic" />
            </div>
            <input
                type="file"
                name="photograph"
                id="photo"
                required="true" />
            <input type="button"
                   id="formBtn"
                   value="Upload Image">
        </form>
    </center>
    <script>
        $(document).ready(() => {
            const photoInp = $("#photo");
            let imgURL;
 
            $('#formBtn').click((e)=>{
                e.preventDefault();
                if(imgURL){
                    alert("The image is uploaded successfully!!");
                }
                else{
                    alert("Please select a Image first!!");
                }
                 
            });
 
            photoInp.change(function (e) {
                imgURL = URL.createObjectURL(e.target.files[0]);
                $("#imgPreview").attr("src", imgURL);
            });
        });
    </script>
</body>
 
</html>


Output:

prevImageGIF



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads