Search code examples
javascriptjqueryfileinputbase64

Image convert to Base64


<input type="file" id="asd"/>

I would like to get the image in base64 once the user chose that (before submitting the form)

Something like :

$(input).on('change',function(){
  var data = $(this).val().base64file(); // it is not a plugin is just an example
  alert(data);
});

I read about File API and other stuffs, I would like a simple and cross-browsers solution (IE6/IE7 excluded obviously)

Any help appreciated thanks.


Solution

  • function readFile() {
      
      if (!this.files || !this.files[0]) return;
        
      const FR = new FileReader();
        
      FR.addEventListener("load", function(evt) {
        document.querySelector("#img").src         = evt.target.result;
        document.querySelector("#b64").textContent = evt.target.result;
      }); 
        
      FR.readAsDataURL(this.files[0]);
      
    }
    
    document.querySelector("#inp").addEventListener("change", readFile);
    <input id="inp" type="file">
    <p id="b64"></p>
    <img id="img" height="150">

    (P.S: A base64 encoded image (String) 4/3 the size of the original image data)

    Check this answer for multiple images upload.

    Browser support: http://caniuse.com/#search=file%20api
    More info here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader