skip to Main Content

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


  1. 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" class="form-control" type="file" id="formFile">
    
    <div id="top_img" style="height: 484px; width: 1080px; position: relative; top:0; left: 0;"></div>
    Login or Signup to reply.
  2. 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" class="form-control" type="file" id="formFile">
    
    
    <div id="top_img" style="height: 484px; width: 1080px; position: relative; top:0; left: 0;"></div>
    Login or Signup to reply.
  3. instead of using the filereader use URL.createObjectURL

    function readURL(input) {
      if (input.files[0]) {
        const url = URL.createObjectURL(input.files[0])
        $("#top_img").css("background-image", `url(${url}`))
        $("#top_img").css("background-size", "cover")
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search