简体   繁体   中英

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

I have a Base64 binary string that is part of an XML document that is sent to us by a 3rd party supplier, I would like to be able to save it back to its 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 to a jpg with little effort, so I know the string is in good form and is a JPG file.

But how do I do this in Delphi 2007?

Looking on the net I found a tutorial on how to convert the Base64 into a TByteDynArray, and save that, but it doesn't work right. I have also played about with Indy's IdDecoderMIME, but with with no success.

Does any one know how to do this, or where I should be looking?

OmniXMLUtils.pas from the OmniXML project contains 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;

The Base64Decode(string, TStream) should do the trick. For the TStream parameter you can pass it TFileStream like this:

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;

Internet Direct(Indy)库在IdCoderMIME.pas中包含支持Base64编码且易于使用的类:TIdEncoderMIME和TIdDecoderMIME。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM