0

I have encoded the image file using base64 encoding. After encoding i can see the value in function itself(function which encodes the image in base64.) using alert. when i try to save this value in variable, it gives "undefined" result

here is my javascript code.

 function getBase64(file) {
       var reader = new FileReader();
       var data="";
       reader.readAsDataURL(file);

       reader.onload = function () {  
        var temp=reader.result.replace(/^data:image\/png;base64,/,"");
        alert("inside fn:"+temp);
        return temp;

       };
       reader.onerror = function (error) {
         console.log('Error: ', error);
       };
    }    


    $(document).ready(function(){


        $("#createLAF").click(function(){

              var files = document.getElementById('panFile').files;
              if (files.length > 0) {
            alert("Outside data:"+getBase64(files[0]));
            }

I get the encoded value in when i hit alert(inside fn.) but don't find value in second alert i.e. alert(outside data:)

Please help to sort out the problem. My main is to convert image file into string in javascript. You can suggest alternate solution also. Thanks in advance.

Nico
  • 6,259
  • 4
  • 24
  • 40
Nitin
  • 11
  • 7

1 Answers1

0

You need to provide some callback mechanism for your getBase64 function because the asynchronous nature of reading a file. You second alert is executed before the data is read. You can do something like this:

$(document).ready(function(){

    var getBase64 = function(file, callback) {
       var reader = new FileReader();
       var data="";
       reader.readAsDataURL(file);

       reader.onload = function () {  
         var temp = reader.result.replace(/^data:image\/png;base64,/,"");
         callback(temp);
       };

       reader.onerror = function (error) {
         console.log('Error: ', error);
       };
    }

    $("#createLAF").click(function(){
       var files = document.getElementById('panFile').files;
       if (files.length > 0) {
          getBase64(files[0], alertData);              
       }
    });

     var alertData = function(data){
        alert("Outside data:"+ data);
     }
});
kevinSpaceyIsKeyserSöze
  • 3,693
  • 2
  • 16
  • 25