Blog

All Blog Posts  |  Next Post  |  Previous Post

FNC Code Gems: Helpers for Base64 encoding and decoding

Friday, July 19, 2019



In the last post, I looked at methods to help you get information about connected displays and determine the path name for common folders. Let’s look at something very valuable when you want to convert binary data into a string: Base64 encoding.This is somewhat tricky if you have to consider all the different platforms and frameworks. FNC makes it very easy!

Again, the class TTMSFNCUtils offers awesome methods to get results quickly:

class function FileToBase64(const AFile: TTMSFNCUtilsFile): string;
   
class function Decode64(const AValue: string; 
                        const AURL: Boolean = False): string;
class function Encode64(const AValue: string; 
                        const AURL: Boolean = False): string; overload;
class function Encode64(const AValue: TBytes; 
                        const AURL: Boolean = False): string; overload;  


Not only are there methods to encode and decode strings, there is also FileToBase64 which allows you to retrieve the Base64 string for a file using a single line of code:

LBase64String := TTMSFNCUtils.FileToBase64( 'mydata.bin' );


Ignore the data type of AFile to specify the filename. In VCL and FMX the type TTMSFNCUtilsFile it is mapped to a string. However, for web applications you cannot specify a local file name and the method has to be invoked differently. There is no inverse function for this as it is already a one-liner in Delphi now to store a string or a byte array into a file using TFile from System.IOUtils.

In order to encode a string, call Encode64; call Decode64 to decode a string:

LMyBase64String := TTMSFNCUtils.Encode64( 'testtest', false );
LMyTestString   := TTMSFNCUtils.Decode64( LMyBase64String, false );


Remember, these methods are available for VCL, FMX, LCL, and TMS Web Core.



Holger Flick




This blog post has not received any comments yet.



Add a new comment

You will receive a confirmation mail with a link to validate your comment, please use a valid email address.
All fields are required.



All Blog Posts  |  Next Post  |  Previous Post