To read the contents of the supplied file, utilize the JavaScript readAsDataURL() function of the FileReader object. The readyState changes to DONE after the read process is complete, and the loadend is then triggered. The file's contents are returned by the FileReader result property.
Let's have a look at the example below, which shows how to read an image file this way and preview it in the browser before uploading it to the server.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Preview an Image Before it is Uploaded Using jQuery</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" class="image" name="photo" onchange="previewFile(this);" required>
</p>
<img id="previewImg" src="" alt="Placeholder">
<p>
<input type="submit" value="Submit">
</p>
</form>
<script type="text/javascript">
$('.image').change(function () {
let reader = new FileReader();
reader.onload = (e) => {
$('#previewImg').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
});
</script>
</body>
</html>
Share