Search code examples
javascripthtmlformscamerabackground-image

Html use file from user and set as background?


I have this code for choosing a file in HTML, and I want to allow the user to choose a file, and then be able to set it as the background. Heres the code for choosing the file

<form id="form1" name="form1" enctype="multipart/form-data">
   <input type="file" id="file1"  name="file1" accept="image/*" capture="camera">
<br>
   <input type="button" value="Save" onclick="sendFile();" />
</form>

Or is there a way I could access the camera of the user in HTML? Basically, I want the user to be able to choose an image or take an image, and then set the image as the background.


Solution

  • Yes we can take advantage the browser's FileReader API to read files and use the file on client side Below is a typical example of using the FileReader API for your use case:

    function sendFile() {
      // IN YOUR ACTUAL CODE REPLACE DEMODIV WITH
      // document.body or the body of your html
      const demoDiv = document.querySelector('#demo');
      const file = document.querySelector('#file1').files[0];
      const reader = new FileReader();
    
      reader.addEventListener("load", function () {
        // setting image file convert to base64 string as demoDiv's background
        demoDiv.style.backgroundImage = `url(${reader.result})`;
      }, false);
    
      if (file) {
        reader.readAsDataURL(file);
      }
    }
    #demo {
      width: 100%;
      height: 400px;
     }
    <form id="form1" name="form1" enctype="multipart/form-data">
       <input type="file" id="file1"  name="file1" accept="image/*" capture="camera">
    <br>
       <input type="button" value="Save" onclick="sendFile();" />
    </form>
    
    <div id="demo"></div>

    Reference: reader.readFileAsDataUrl