How to Preview an Image Before it is Uploaded Using jQuery

  2134 views   2 years ago jQuery

Use the JS readAsDataURL() Method

You can use the JavaScript readAsDataURL() method of the FileReader object to read the contents of the specified file. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. The FileReader result property returns the file's contents.

Let's try out the following example which demonstrates how to read an image file using this method and preview it in the browser before it is uploaded on the server.

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>jQuery Preview an Image Before it is Uploaded</title>
<script src=""></script>
    function previewFile(input){
        var file = $("input[type=file]").get(0).files[0];
            var reader = new FileReader();
            reader.onload = function(){
                $("#previewImg").attr("src", reader.result);
    <form action="confirmation.php" method="post">
            <input type="file" name="photo" onchange="previewFile(this);" required>
        <img id="previewImg" src="/examples/images/transparent.png" alt="Placeholder">
            <input type="submit" value="Submit">


Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]