Image Preview Before Upload By Using JS

Training Mode Regular Fastrack Crash
Classroom | Online
Course Description :
Solution : 

Step1 : 
Write following html code 
<img src="<?php echo base_url();?>assets/images/avatar.jpg" style="height:80px;" id="avtar">
<input type="file" id="avtarbtn" name="docpic" class="form-control" value="">

Step2 :  Paste the following script at the end of body tag

<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#avtar').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#avtarbtn").change(function() {
//alert("hello");
readURL(this);
});
</script>

Complete Code :

<!DOCTYPE html>
<html lang="en">
<head>
<title>Image Preview</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">

<div class="form-group row">
<label for="Doctor" class="form-label col-form-label col-sm-4">Doctor Profile Image
</label>
<div class="col-sm-8">
<img src="<?php echo base_url();?>assets/images/avatar.jpg" style="height:80px;" id="avtar">
<input type="file" id="avtarbtn" name="docpic" class="form-control" value="">
</div>
</div>
</div>
 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#avtar').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#avtarbtn").change(function() {
//alert("hello");
readURL(this);
});
</script>
</body>
</html>

 

 

Request a Demo

Whatsapp