How To Preview Image Before Upload In jQuery

Websolutionstuff | Jul-15-2022 | Categories : PHP jQuery

In this article, we will see how to preview an image before uploading it in jquery. You can use the JavaScript readAsDataURL() method of the FileReader object to read the contents of the specified file. The readAsDataURL the method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered.

So, let's see the preview image before uploading javascript, preview images using jquery.

Example:

how to read an image file using this method and preview it in the browser before it is uploaded to the server.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>How To Preview Image Before Upload In jQuery - Websolutionstuff</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    function previewFile(input){
        var file = $("input[type=file]").get(0).files[0];
 
        if(file){
            var reader = new FileReader();
 
            reader.onload = function(){
                $("#previewImg").attr("src", reader.result);
            }
 
            reader.readAsDataURL(file);
        }
    }
</script>
</head> 
<body>
    <form action="image_upload.php" method="post">
        <p>
            <input type="file" name="image_file" onchange="previewFile(this);" required>
        </p>
        <img id="previewImg" src="/images/example.png" alt="Placeholder">
        <p>
            <input type="submit" value="Submit">
        </p>
    </form>
</body>
</html>

 


You might also like:

Recommended Post
Featured Post
How To Bind Data In React JS
How To Bind Data In React JS

In this article, we will see how to bind data in React JS. Also, we will see how to bind the variable value in the...

Read More

Aug-19-2022

MilesWeb Review: Why Go for Its Shared Hosting?
MilesWeb Review: Why Go for It...

For finding the right web hosting provider, you need to do a lot of research. There are hundreds of web hosting provider...

Read More

Nov-12-2021

How to Create Bar Chart in Vue 3 using vue-chartjs
How to Create Bar Chart in Vue...

Hello, web developers! In this article, we'll see how to create a bar chart in vue 3 using vue-chartjs. Here, w...

Read More

Jul-31-2024

How To Block IP Address In Laravel 10
How To Block IP Address In Lar...

In this article, we will see how to block IP addresses in laravel 10. Here we will learn about how to restrict...

Read More

May-17-2023