Home > Misc > HTML & JScript – Read and Encode file

HTML & JScript – Read and Encode file

We got a requirement in ADX portal, to read and convert the file content to Base64String , which eventually will be submitted to an external API.

Below is the code snippet to read the File content, browsed using the HTML ‘File Upload’ control:

function readFileAsText(){
try {
// Read the browsed file from ‘File Upload’ control.
var fileToLoad = document.getElementById(“fileOE“).files[0];

var fileReader = new FileReader();
fileReader.onload = function (fileLoadedEvent) {
// Set the file content to variable
var textFromFileLoaded = fileLoadedEvent.target.result;
alert(“File Content – ” + textFromFileLoaded);

// Using ‘window.btoa’ encode the plain text to Base 64
var convertedString = window.btoa(unescape(encodeURIComponent(textFromFileLoaded)));
alert(“Base 64 content – ” + convertedString);
};

fileReader.readAsText(fileToLoad, “UTF-8”);
} catch (e) {
alert(“Error in readFileAsText(); Error – ” + e.description);
}
}

<body>
<label for=”fileOE”>Pick the file </label><br>
<input type=”file” id=”fileOE” />
<input type=”button” value=”Upload” onclick=”readFileAsText()” />
</body>

  • Execute the code and you will get output as below
jScript_1

File content as text

jScript_2

Encoded File Content (Base 64)

🙂

Advertisement
Categories: Misc Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: