How to Preview an Image Before Uploading it in Jquery
1 year ago
admin
Jquery
In this lesson, we will see how to preview an image before uploading it in jquery, let's assume that we want to add a blog post and we want to preview the image before uploading it, so let's see how we can do that.
Preview image before uploading it
So to do that you can use the code below:
<!DOCTYPE html>
<html>
<head>
<style>
.d-none {
display:none
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
function readURL(input,image) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#' + image).removeClass('d-none');
$('#' + image).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#image").change(function(){
readURL(this,'image_preview');
});
});
</script>
</head>
<body>
<form action="">
<input type="file" id="image">
<img src="#" id="image_preview" class="d-none" width="100" height="100">
</form>
</body>
</html>