0

I am trying to upload a file using input[type=file] and at form submit (which contains other elements like "first name", "last name" etc), I am converting the file to string and pass it as JSON to a server.

HTML:

<input type="file" class="form-control" id="resume" accept=".doc, .docx, .pdf" />

Script:

var resume = document.getElementById('resume').files[0];
var result = getbase64(resume);
console.log(result); 

This returns undefined but the console.log inside the actual method logs the correct content when the above line calls the method.

function getBase64(file) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
        var result = reader.result;
        console.log('here---->   '+result);
        return result;
    };
    reader.onerror = function (error) {
        console.log('Error: ', error);
    };
} 

My question is how to correctly assign this return type to a variable so I can send it as String to the server.

Adriano
  • 3,788
  • 5
  • 32
  • 53
sf_user
  • 168
  • 1
  • 2
  • 9

1 Answers1

1

Your return statement return result does not return what you expect since it is in an event listener. That is, the output of function getBase64 will be Undefined. You can simply pass a callback function to transfer the file when the load event happens.

function getBase64(file, transferMyFile) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
        var result = reader.result;
        console.log('here---->   '+result);
        transferMyFile(result)
        /* Or just transfer it here */
    };
    reader.onerror = function (error) {
        console.log('Error: ', error);
    };
} 
MTMD
  • 1,162
  • 2
  • 11
  • 23