Q:

How to Preview an Image Before it is Uploaded Using jQuery

0

How to Preview an Image Before it is Uploaded Using jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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">
<head>
<meta charset="utf-8">
<title>jQuery Preview an Image Before it is Uploaded</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="confirmation.php" method="post">
        <p>
            <input type="file" name="photo" onchange="previewFile(this);" required>
        </p>
        <img id="previewImg" src="/examples/images/transparent.png" alt="Placeholder">
        <p>
            <input type="submit" value="Submit">
        </p>
    </form>
</body>
</html>

We've used a transparent image of 1x1 pixels as a placeholder for the preview image. This is to prevent the browser from showing the default image placeholder for non-existent image.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get Class Name Using jQuery... >>
<< How to Show Loading Spinner in jQuery...