Saving a Base64 string to disk as a binary using Delphi 2007

I have a Base64 binary string, which is part of an XML document that is sent to us by a third-party provider, I would like to save it back to the original file format (jpg).

Using the accepted answer from this question "saving a base64 string to disk as a binary using php" I can save the string in jpg with little effort, so I know that the string is in good shape and is a JPG file.

But how do I do this in Delphi 2007?

Looking at the network, I found a tutorial on how to convert Base64 to TByteDynArray and save it, but this does not work correctly. I also played with Indy IdDecoderMIME, but without success.

Does anyone know how to do this or where should I look?

+1
source share
2 answers

OmniXMLUtils.pas from the OmniXML project contains the following functions:

function  Base64Decode(encoded, decoded: TStream): boolean; overload;
function  Base64Decode(const encoded: string; decoded: TStream): boolean; overload;
function  Base64Decode(const encoded: string; var decoded: string): boolean; overload;
function  Base64Decode(const encoded: string): string; overload;
procedure Base64Encode(decoded, encoded: TStream); overload;
procedure Base64Encode(decoded: TStream; var encoded: string); overload;
function  Base64Encode(decoded: TStream): string; overload;
function  Base64Encode(const decoded: string): string; overload;
procedure Base64Encode(const decoded: string; var encoded: string); overload;

Base64Decode (string, TStream) should do the trick. For the TStream parameter, you can pass it to TFileStream as follows:

procedure SaveBase64ToFile(const encoded, fileName: string);
var
  fs: TFileStream;
begin
  fs := TFileStream.Create(fileName, fmCreate);
  try
    if not Base64Decode(encoded, fs) then
      raise Exception.Create('Invalid data!');
  finally FreeAndNil(fs); end;
end;
+7
source

The Internet Direct (Indy) library contains classes in IdCoderMIME.pas that support Base64 encoding and are easy to use: TIdEncoderMIME and TIdDecoderMIME.

0
source

Source: https://habr.com/ru/post/1716659/


All Articles