File to Base64 with JavaScript

To convert a String to/from Base64 in JavaScript, we use the btoa and atob commands.

Here is another code to convert a file to Base64:

ToBase64.htm

<script>
async function readTextFileAsBlob(file) {
    const response = await fetch(file);
    const blob = await response.blob();
    return blob;
}

const blobToBase64DataURL = blob => new Promise(  
    resolvePromise => {
        const reader = new FileReader();
        reader.onload = () => resolvePromise(reader.result);
        reader.readAsDataURL(blob);
    }
);

my_file = AppInventor.getWebViewString(); // INPUT
readTextFileAsBlob(my_file).then(
    async blob => {
        const base64URL = await blobToBase64DataURL(blob);
	 //	  document.write(base64URL);
	      AppInventor.setWebViewString(base64URL); // OUTPUT
    }
);
</script>

p70_base64_javascript.aia (11.4 KB)

base64javascript1

This has promise :slight_smile:
Does the readTextFileAsBlob function also work for other file types, e.g. image, pdf, zip?

I think so, in the app I have put a .png file.

Now trying to return base64 to readable string wit atob.

my_file = AppInventor.getWebViewString(); // INPUT
readTextFileAsBlob(my_file).then(
    async blob => {
        const base64URL = await blobToBase64DataURL(blob);
	 //	  document.write(base64URL);
	  // AppInventor.setWebViewString(base64URL); // OUTPUT
	  var my_file2 =  atob(base64URL.substring(23));
      AppInventor.setWebViewString(my_file2); // OUTPUT
    }
);

1.- Image in asset. JavaScript encode image ToBase64 String. Return String. String to Files by Canvas Block and extension. Files in ASD.

p70_base64_javascript_v3.aia (33.9 KB)

ToBase64.htm

<script>
async function readTextFileAsBlob(file) {
    const response = await fetch(file);
    const blob = await response.blob();
    return blob;
}

const blobToBase64DataURL = blob => new Promise(  
    resolvePromise => {
        const reader = new FileReader();
        reader.onload = () => resolvePromise(reader.result);
        reader.readAsDataURL(blob);
    }
);

my_file = AppInventor.getWebViewString(); // INPUT
readTextFileAsBlob(my_file).then(
    async blob => {
        const base64URL = await blobToBase64DataURL(blob);
               // .split("base64,")[1]) to remove data:image/png;base64,
	     AppInventor.setWebViewString(base64URL.split("base64,")[1]); // OUTPUT    
    }
);
</script>
1 Like