Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting backgroundImage style from a FileReader

I am looking for a solution that allows me to take a file from a file upload input and preview it by setting the document.body.style.backgroundImage.

The following code works to display a preview in an Image element:

function setImage(id, target){
  input = document.getElementById(id);
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      target.src = e.target.result;
    };

        reader.readAsDataURL(input.files[0]);
  }
}

Where id is the id of the <input type='file'>, and target is the <img> element.

The following code outlines what I would like to happen, however e.target.result is of data:image/png;base64 format and clearly does not work where css requests a url.

  function setBackgroundImage(id){
    input = document.getElementById(id);
    if (input.files && input.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
          document.body.style.backgroundImage = e.target.result;
      };

      reader.readAsDataURL(input.files[0]);
    }
  }

Thank you for your help!

like image 426
GAgnew Avatar asked Jul 12 '11 18:07

GAgnew


1 Answers

You need to use url() around the URL:

document.body.style.backgroundImage = 'url(' + e.target.result + ')';
like image 58
Guffa Avatar answered Nov 13 '22 11:11

Guffa