Setting backgroundImage style from a FileReader

旧街凉风 提交于 2019-12-22 04:13:08

问题


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!


回答1:


You need to use url() around the URL:

document.body.style.backgroundImage = 'url(' + e.target.result + ')';


来源:https://stackoverflow.com/questions/6669228/setting-backgroundimage-style-from-a-filereader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!