I need to grab the browse image upload url and apply it as a background cover to a div, and this is what I’ve tried but i don’t get the background image:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$("#top_img").css("background-image", e.target.result);
$("#top_img").css("background-size", "cover");
}
reader.readAsDataURL(input.files[0]);
}
}
$("#upload").change(function() {
readURL(this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="upload" class="form-control" type="file" id="formFile">
<div id="top_img" style="height: 484px; width: 1080px; position: relative; top:0; left: 0;"></div>
3
Answers
You need to wrap the image with
url()
:Problem is that you need to include
url()
when setting the background-image, so use:Demo
instead of using the filereader use
URL.createObjectURL