Base64 to Binary (Delphi)

前端 未结 5 817
灰色年华
灰色年华 2021-01-03 05:47

I used Binary to Base64 function that you answered : Binary to Base64 (Delphi)

I successfully encode a file to base64 string and write it to MsSQL2008 database, but

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-03 06:25

    This function will take a base64 encoded string, decode it, and write the resulting byte array to a file.

    procedure DecodeToFile(const base64: AnsiString; const FileName: string);
    var
      stream: TFileStream;
      bytes: TBytes;
    begin
      bytes := DecodeBase64(base64);
      stream := TFileStream.Create(FileName, fmCreate);
      try
        if bytes<>nil then
          stream.Write(bytes[0], Length(Bytes));
      finally
        stream.Free;
      end;
    end;
    

    To explain what is happening here, the first line

    bytes := DecodeBase64(base64);
    

    performs the decode and returns the decoded binary contents of the file in a TBytes variable. TBytes is simply an array of bytes.

    The next step is to create the file. The idiomatic way to write files in Delphi is to use streams. In this case we want a TFileStream.

    stream := TFileStream.Create(FileName, fmCreate);
    

    The fmCreate option means that if the file already exists, it will be replaced and overwritten by what we write.

    The final step is to write the contents of the byte array to the file

    if bytes<>nil then
      stream.Write(bytes[0], Length(Bytes));
    

    The if bytes<>nil check is to handle the case where the base64 string decodes to an empty array. If we were to remove that check then the following line would result in a runtime error if you were running with range checking enabled (which you should be doing). The call to stream.Write should be self-explanatory.

提交回复
热议问题