从FileReader设置backgroundImage样式 [英] Setting backgroundImage style from a FileReader

查看:74
本文介绍了从FileReader设置backgroundImage样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种解决方案,允许我从文件上传输入中提取文件并通过设置document.body.style.backgroundImage进行预览.

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.

以下代码可在Image元素中显示预览:

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]);
  }
}

其中id是<input type='file'>的id,目标是<img>元素.

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

以下代码概述了我想发生的情况,但是e.target.result为data:image/png;base64格式,显然在css请求url的地方不起作用.

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]);
    }
  }

谢谢您的帮助!

推荐答案

您需要在URL周围使用url():

You need to use url() around the URL:

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

这篇关于从FileReader设置backgroundImage样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆