You may want to consider using jQuery to achieve this functionality. Below is an example that demonstrates how it can be done.
Here is the code snippet for creating a preview:
function displayImage(input) {
var identifier = $(input).attr("id");
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('label[for="' + identifier + '"] .upload-icon').css("border", "none");
$('label[for="' + identifier + '"] .icon').hide();
$('label[for="' + identifier + '"] .prev').attr('src', e.target.result).show();
}
reader.readAsDataURL(input.files[0]);
}
}
$("input[id^='file-input']").change(function() {
displayImage(this);
});
I have made it more dynamic so you can use the input field multiple times, similar to your image example.
Hopefully, this solution proves to be helpful for you.
function displayImage(input) {
var identifier = $(input).attr("id");
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('label[for="' + identifier + '"] .upload-icon').css("border", "none");
$('label[for="' + identifier + '"] .icon').hide();
$('label[for="' + identifier + '"] .prev').attr('src', e.target.result).show();
}
reader.readAsDataURL(input.files[0]);
}
}
$("input[id^='file-input']").change(function() {
displayImage(this);
});
.image-upload>input {
display: none;
}
.upload-icon {
width: 100px;
height: 97px;
border: 2px solid #5642BE;
border-style: dotted;
border-radius: 18px;
float: left;
}
.upload-icon .icon {
width: 60px;
height: 60px;
margin: 19px;
cursor: pointer;
}
.prev {
display: none;
width: 95px;
height: 92px;
margin: 2px;
border-radius: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="image-upload">
<label for="file-input">
<div class="upload-icon">
<img class="icon" src="https://image.flaticon.com/icons/png/128/61/61112.png">
<img class="prev" src="https://image.flaticon.com/icons/png/128/61/61112.png">
</div>
</label>
<input id="file-input" type="file" />
</div>
<div class="image-upload">
<label for="file-input2">
<div class="upload-icon">
<img class="icon" src="https://image.flaticon.com/icons/png/128/61/61112.png">
<img class="prev" src="https://image.flaticon.com/icons/png/128/61/61112.png">
</div>
</label>
<input id="file-input2" type="file" />
</div>
<div class="image-upload">
<label for="file-input3">
<div class="upload-icon">
<img class="icon" src="https://image.flaticon.com/icons/png/128/61/61112.png">
<img class="prev" src="https://image.flaticon.com/icons/png/128/61/61112.png">
</div>
</label>
<input id="file-input3" type="file" />
</div>
</form>