0

How can I convert a base64 string returned by reader.readDataAsUrl() to a string which looks exactely the same.

Javascript:

function getBase64(file) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
        return reader.result;
    };
    reader.onerror = function (error) {
        console.log('Error: ', error);
        return false;
    };
} // works and returns a base64 version of the image

but when I do typeof(getBase64(...)) it says undefined.

So how can I convert this base64 'string' to a real string

Background: I want to have a string and remove the "=" at the end as result

Edit/Solution: I wasn't aware that reader.readAsDataURL is an asynchronous function and I had to wait for reader.onload().

Fipsi
  • 670
  • 1
  • 9
  • 21
  • `works and returns a base64 version of the image` I doubt it, that function doesn't return anything – Jaromanda X Oct 06 '18 at 09:34
  • `getBase64` doesn't return value, so you get `undefined`, that is normal. – ElJackiste Oct 06 '18 at 09:35
  • 1
    `reader.onload` is **asynchronous** and returning from that function doesn't return from getBase64 - which has already returned nothing before onload is even called (hence asynchrony) - you'll need a callback – Jaromanda X Oct 06 '18 at 09:35
  • 1
    `how can I convert this base64 'string' to a real string` what do you mean "real"? it is a "real" string ... full of characters 0-9,a-z,A-Z,+,/ and = ... they're all real! – Jaromanda X Oct 06 '18 at 09:41

1 Answers1

1

Based on your code, you can do something similar to that :

function getBase64(file, callback) {
  var reader = new FileReader();
  reader.readAsDataURL(file.files[0]); 
  reader.onload = function() {
    callback(reader.result.substring(22)); // change data url format to "real" base64
  };
  reader.onerror = function(error) {
    console.log('Error: ', error);
    return false;
  };
}

document.querySelector('input[type="file"]').addEventListener('change', function () {
  getBase64(this, function (result) {
    var decode = atob(result); // decode image
    var encode = btoa(decode); // encode image again in Base64
    console.log(result); // Base64 image
    console.log(decode); // Image decoded
    console.log(encode); // Base64 image
  });
});
<input type="file"><br>

readAsDataURL return a base64 data formatted. You should remove the data formatted part by using substring for example to have a "real" base64.

References : readAsDataUrl MDN Reference - data base64 MDN Reference

ElJackiste
  • 4,011
  • 5
  • 23
  • 36