This prints base64 out to console:
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
console.log(reader.result);
};
reader.onerror = function(error) {
console.log('Error: ', error);
};
}
var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file); // prints the base64 string
Source: https://stackoverflow.com/a/36281449/1063287
jsFiddle: jsFiddle demo of the above working code
I want to be able to assign the base64 to a variable, so I tried the following, based on this answer:
function getBase64(file, onLoadCallback) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = onLoadCallback;
reader.onerror = function(error) {
console.log('Error when converting PDF file to base64: ', error);
};
}
var my_pdf_file = document.querySelector("#my_pdf_file").files[0];
var my_pdf_file_as_base64 = "";
getBase64(my_pdf_file, function(e) {
my_pdf_file_as_base64 = e.target.result
});
// print out the base64 to show i have captured the value correctly
console.log(my_pdf_file_as_base64);
It is currently printing nothing out to the console.
Question:
How can I save the base64 value as a variable?
Edit:
As requested, for context:
I am submitting a form in a Google Apps Script environment.
I have done this previously and passed a form object (which included a file) through to the Google Apps Script function.
However, one of the constraints of this approach is that if passing a form object as a parameter, it is the only parameter allowed.
A form element within the page is also legal as a parameter, but it must be the function’s only parameter
In this instance, I am passing multiple parameters through, and one of the parameters will be a pdf file, converted to base64.
In response to @Aasmund's great answer, I would like the variable assignment to block further code execution:
var my_pdf_file = [ converted file here ];
// don't do this stuff until the above variable is assigned
Otherwise, I will have to refactor the remaining code to take place in the then
block (suggested by @Aasmund), and that might be messy / impossible due to the amount of validation / variable preparation / conditional handling that is taking place before the form is submitted.