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

谁说胖子不能爱 提交于 2019-12-08 15:33:55

问题


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.


回答1:


You need to read the contents of the selected file using HTML5 FileReader API then get base64 encoded Data-URL of it. Then you can set this URL as background of anything.

If you don't know Data-URL is a type of URI that does not point to the location of a file, rather it holds the whole content of the file in base64 encoded format inside the URL. Any file can be converted to a Data-URL. You can read more about it here.

Note: Data-URI is only preferred for small files. Do not convert megabyte size files into Data-URI.

function previewFile(fileInput) {
  var file = fileInput.files[0];
  var reader = new FileReader();

  reader.addEventListener("load", function() {
    setBackground(reader.result);
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
}
function setBackground(imageURL){
    document.body.style.backgroundImage = "url(" + imageURL + ")";
    document.body.style.backgroundSize = "100% auto";
    document.body.style.backgroundRepeat = "no-repeat";
    document.body.style.backgroundPosition = "center top";
}
<input type="file" onchange="previewFile(this);">



回答2:


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">


来源:https://stackoverflow.com/questions/48890876/how-to-set-an-image-as-a-background-image-in-html-using-input-type-file

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