0

I need to convert an uploaded file into a base64, and pass it to a Web Api as a parameter.

In the examples if i write to console the reader.result it write the correct base64 result, but if i return it as a return var, i obtain an Undefined.

So i can't retrieve the result from this function, because i have to pass it to the ajax call.

How can i wait for the completation of the encoding, and get the result?

Thank u all

 function getBase64(file) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      return (reader.result);
    };
    reader.onerror = function (error) {
      return ('Error: ', error);
    };
  }
$(document).ready(function () {

var base64File;
var files = document.getElementById('file').files; // uploaded file
if (files.length > 0) {
    base64File = getBase64(files[0]);
} 

console.log(base64File) // undefined 

});
Fadelast
  • 5
  • 1
  • 5

1 Answers1

0

The getBase64 function returns only a console log, shouldn't it return reader.result?

Kim Kakan Andersson
  • 548
  • 1
  • 5
  • 15
  • yes, it should but the encoding reading require some time and, the function result become undefined (anyway i modify the code to be clearer) – Fadelast May 04 '21 at 17:29
  • The answer on this link should probably help you https://stackoverflow.com/questions/11829537/html5-filereader-how-to-return-result – Kim Kakan Andersson May 04 '21 at 17:33
  • i'll try to read it thanks, the callback of js is something i cant' understand at all – Fadelast May 04 '21 at 17:50