search

Home  >  Q&A  >  body text

How to use an image from an uploaded file in HTML as a background?

I'm trying to use to allow the 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.

This is the input I'm trying to use: This is the JavaScript associated with the input Background = selectBackground.value; document.body.style.background = "#4d3325 url('" background "') No repeating center center fixed"; document.body.style.backgroundSize = "Auto 100%";

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

P粉920199761P粉920199761445 days ago530

reply all(2)I'll reply

  • P粉134288794

    P粉1342887942023-09-09 12:19:27

    Hi friends, please check if this solution meets 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>

    reply
    0
  • P粉821231319

    P粉8212313192023-09-09 09:38:53

    Use URL.createObjectURL()

    By using this function, the uploaded image file will be converted into an object url.

    Finally, when we change other images, we should use URL.revokeObjectURL() to remove the old url from memory for better memory management.

    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)">

    reply
    0
  • Cancelreply