0

i need to upload an image by an input file, convert it to base64 and send it to an API using ajax. I can convert the image but can't return the base64 into a variable to make the json. Here is my code:

HTML

<input id="picture" type="file">

JS

const picture = document.getElementById("picture")

function loadImageFileAsURL() {
    var filesSelected = picture.files;
    if (filesSelected.length > 0) {
        var fileToLoad = filesSelected[0];
        var fileReader = new FileReader();

        fileReader.onload = function(fileLoadedEvent) {
            console.log(fileLoadedEvent.target.result);
        }

        fileReader.readAsDataURL(fileToLoad);
    }
}

picture.addEventListener('change', function() {
    loadImageFileAsURL()
})

It returns the base64 image in the console.

So i'm try to save this into a variable changing this: console.log(fileLoadedEvent.target.result); by this: let pictureEnconde = fileLoadedEvent.target.result; but it returns undefined. I don't know what's going on :( i will appreciate your help.

Ken Ramirez
  • 325
  • 5
  • 17

1 Answers1

0

Here is an Example may help you:

var file=null;

function toBase64(file) {
   var reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     file=reader.result
     console.log(file);
   };
}
<input type="file" onchange="toBase64(this.files[0])">
ferhado
  • 2,363
  • 2
  • 12
  • 35