How to use an image from an uploaded file in HTML as a background?
P粉920199761
P粉920199761 2023-09-08 13:49:16
0
2
517

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粉920199761
P粉920199761

reply all(2)
P粉134288794

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>
P粉821231319

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)">
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!