从FileReader设置backgroundImage样式 [英] Setting backgroundImage style from a FileReader
问题描述
我正在寻找一种解决方案,允许我从文件上传输入中提取文件并通过设置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屋!