Search code examples
javascripthtmlinput-type-file

How to set an image as a background image in html using input type="file"?


I am creating a web page that can receive an image and set it as a background image.

My work till now:

function a(a) {
  document.body.style.backgroundImage = "url(a.value)";
}
<input type="file" onchange="a(this);">

Since the value comes as C:\fakepath\Image.extension, the background doesn't changes. So, can you please help me to do this using javascript only. I know this is a very strange question. But it will help me to learn something new and can help others too.


Solution

  • Simply wrap the File blob into an Object-URL (URL.createObjectURL) and set that as source for the CSS background image.

    This will simplify your code, the image will be processed faster and image size will be less of a problem:

    document.querySelector("input").onchange = function() {
      var url = URL.createObjectURL(this.files[0]);
      document.body.style.background = "url(" + url + ") no-repeat";
    }
    <input type="file">