使用 Delphi 将大文件转换为 base64

Convert large file to base64 with Delphi

我需要将一个文件从 480mb 转换为 base64,但我做不到。我总是得到内存不足的消息。有人有什么建议吗?

function TFormService.LoadFileToBase64(const AFileName: string): String;
var
//  stream: TMemoryStream;
  Encoder: TIdEncoderMIME;
  Base64String: String;
  LStream: TMemoryStream;
begin
  Encoder := TIdEncoderMIME.Create;
  LStream := TMemoryStream.Create;
  try
    LStream.LoadFromFile(AFileName);
    Base64String := Encoder.Encode(LStream);
  finally
    FreeAndNil(Encoder);
    FreeAndNil(LStream);
  end; // try finally


//  stream := TMemoryStream.Create;
//  try
//    stream.LoadFromFile(AFilename);
//    result := EncodeBase64(stream.Memory, stream.Size);
//  finally
//    stream.Free;
//  end;
end;

你不应该在内存中保存整个 Base64 字符串。 480 MB 编码为 Base64 将产生大约 640 M 个字符,占用大约 1.28 GB 内存。这在 32 位应用程序中肯定会失败。

最好将编码后的字符串写入文件并为此使用合适的编码器。最近的 Delphi 版本有 System.NetEncoding

procedure ConvertFileToBase64(const AInFileName, AOutFileName: string);
var
  inStream: TStream;
  outStream: TStream;
begin
  inStream := TFileStream.Create(AInFileName, fmOpenRead);
  try
    outStream := TFileStream.Create(AOutFileName, fmCreate);
    try
      TNetEncoding.Base64.Encode(inStream, outStream);
    finally
      outStream.Free;
    end;
  finally
    inStream.Free;
  end;
end;