Saturday, December 29, 2007

JavaScript: Encode to Base64

Once again, I will not take credit of this one...

// ***
// Encode to Base64
// Warning: Do not use for larger content as the loop might take a while
// ***
function base64Encode(data)
{
if (typeof(btoa) == 'function') return btoa(data);
var b64_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var byte1, byte2, byte3;
var ch1, ch2, ch3, ch4;
var result = new Array();
var j=0;
for (var i=0; i byte1 = data.charCodeAt(i);
byte2 = data.charCodeAt(i+1);
byte3 = data.charCodeAt(i+2);
ch1 = byte1 >> 2;
ch2 = ((byte1 & 3) << 4) | (byte2 >> 4);
ch3 = ((byte2 & 15) << 2) | (byte3 >> 6);
ch4 = byte3 & 63;

if (isNaN(byte2)) {
ch3 = ch4 = 64;
} else if (isNaN(byte3)) {
ch4 = 64;
}

result[j++] = b64_map.charAt(ch1)+b64_map.charAt(ch2)+b64_map.charAt(ch3)+b64_map.charAt(ch4);
}

return result.join('');
}

3 comments:

  1. The code is borked...doesn't run...try re-pasting...

    ReplyDelete
  2. There was probably some copy-paste-format error. I have corrected it. Thanks

    ReplyDelete
  3. THis is VB.NET, but you'll get the gist ... this is much easier (m_FilePathName is a member of my class)
    Public Function FileToBase64() As String
    If System.IO.File.Exists(m_FilePathName) Then
    Dim contents As Byte() = System.IO.File.ReadAllBytes(m_FilePathName)
    Return System.Convert.ToBase64String(contents)
    Else : Throw New InvalidOperationException("FileToBase64 Error: FilePathName does not exist")
    End If
    End Function

    ReplyDelete

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.