On this Page

    _toBase64

    (As of 3.1.002.10)

    Convert a string to Base64 encoding.

    Syntax

    _toBase64(string[, bytesperchar])

    Parameters

    string is the string to be converted. It must contain 8bit characters only (unicode 0-255);

    bytesperchar is the coding size of each character in the string parameter. The default is 1, indicating that each string character is to be treated as a single 8bit value when it is converted. This will be mean that no character in the string is expected to have a Unicode character code greater than 255. To convert the full unicode character set, set bytesperchar to 2.

    Returned Value

    Returns the resulting base64-encoded string.

    Example

     var str = "DocOrigin 2020";
     var b64 = _toBase64(str);	// "RG9jT3JpZ2luIDIwMjA="
     var txt = _fromBase64(b64);	// "DocOrigin 2020"
    
     var str2 = "保险单号";
     var b64 = _toBase64(str2, 2);	// "T92WaVNVU/c="
     var txt = _fromBase64(b64, 2);	// "保险单号"

    Note that as an alternative to encoding 2-byte Unicode directly into base64, you could also convert the Unicode string to UTF-8 first. UTF-8 is a more compact representation where character codes below 128 (the ASCII set) are represented by simple single-byte characters, while others are encoded as 2 or 3 byte sequences.

    The choice is dependent on your intended usage of the base64 encoded string.

     var str = "DocOrigin fête 2020";
     var utf8 = unescape(encodeURIComponent(str)); 	// "DocOrigin fête 2020"
     var b64 = _toBase64(str); 			// "RG9jT3JpZ2luIGbDqnRlIDIwMjA="
     var u = _fromBase64(b64);  			// "DocOrigin fête 2020"
     var txt = decodeURIComponent(escape(u));	// back to "DocOrigin fête 2020"

    See Also

    _fromBase64
    _file.toBase64
    _file.fromBase64