Home > Blockchain >  How to apply url url uploaded as css background?
How to apply url url uploaded as css background?

Time:10-27

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"  type="file" id="formFile">

<div id="top_img" style="height: 484px; width: 1080px; position: relative; top:0; left: 0;"></div>

CodePudding user response:

Problem is that you need to include url() when setting the background-image, so use:

$("#top_img").css("background-image", `url(${e.target.result})`);

Demo

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
    console.log("T",e.target.result)
      $("#top_img").css("background-image", `url(${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"  type="file" id="formFile">


<div id="top_img" style="height: 484px; width: 1080px; position: relative; top:0; left: 0;"></div>

CodePudding user response:

You need to wrap the image with url():

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      console.log(e.target.result);
      $("#top_img").css("background-image", `url(${e.target.result})`); // That's the change
      $("#top_img").css("background-size", "cover");
    }
    reader.readAsDataURL(input.files[0]);
  }
}
$("#upload").change(function(e) {
  readURL(this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input id="upload"  type="file" id="formFile">

<div id="top_img" style="height: 484px; width: 1080px; position: relative; top:0; left: 0;"></div>

  • Related