skip to Main Content

I’m trying to use <input type="file"> to allow a user to upload an image that will be used as a background. I don’t know if I need to get the full path of the file or not.

This is the input I’m trying to use: <input type="file" name="selectBackground" id="selectBackground" accept="image/png, image/jpeg">
This is the JavaScript associated with the input
background = selectBackground.value; document.body.style.background = "#4d3325 url('" + background + "')no-repeat center center fixed"; document.body.style.backgroundSize = "auto 100%";

The background doesn’t change at all and when I try to display it as a regular image, it just shows a small image icon.

2

Answers


  1. Hi friend check if this solution attends your needs:

    var input = document.getElementById('input');
    input.addEventListener('change', readURL, true);
    
    function readURL() {
      var file = document.getElementById("input").files[0];
      var reader = new FileReader();
      reader.onloadend = function() {
        var image = new Image();
    
        image.src = reader.result;
    
        image.onload = function() {
          document.getElementById("myDiv").style.backgroundImage = "url(" + reader.result + ")";
        }
      }
      if (file) {
        reader.readAsDataURL(file);
      }
    }
    <div id="myDiv" style="width:200px; height:200px">
      <input type="file" id="input" class="custom-file-input" accept=".png, .jpg, .jpeg, .gif .bmp" />
    </div>
    Login or Signup to reply.
  2. Use URL.createObjectURL()

    By using this, the uploaded image file is converted in to object url.

    Finally when we change the other image we should remove the old url from memory for better memory management by using URL.revokeObjectURL().

    function file(e){
                   window.url && URL.revokeObjectURL(window.url);// release memory
                   const f = e.target.files[0];
                   let url = URL.createObjectURL(f);
                   window.url = url;
                   document.getElementsByClassName('container')[0].style.backgroundImage = `url(${url})`;
    }
    .container{
            width: 100px;
            height: 100px;
            border: 1px solid lightgrey;
            margin: 10px;
            background-size: contain;
            background-repeat: no-repeat;
    }
     <div class='container'></div>
     <input type='file' accept=".png, .jpg, .jpeg, .gif .bmp" onchange="file(event)">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search