Delphi TNetEncoding.Base64 works but data are cutted

222 views Asked by At

I have this code, in which I want to convert a file to Base64 format using TNetEncoding.Base64. It works, but it cuts my data to a few lines. My question is why? Delphi's String can contains approx 230 characters, or 2GB of data, so why does this not work properly?

I want to use this conversion for PDF files approx 3-6MB and store these strings into an SQL database (this isn't shown in the code example).

procedure TForm1.Button1Click(Sender: TObject);
var
  inp: String;
  s: string;
begin
  try
    if OpenDialog1.Execute then
      if FileExists(OpenDialog1.FileName) then
      begin
        Memo1.Lines.LoadFromFile(OpenDialog1.FileName);
        s := TNetEncoding.Base64.Encode(Memo1.Lines.Text);
      end;

    memo1.Lines.Text := s;
  except
    ShowMessage('error');
  end;
1

There are 1 answers

2
Remy Lebeau On

First off, rather than using FileExists() after TOpenDialog.Execute() return True, you should instead enable TOpenDialog's ofPathMustExist and ofFileMustExist options, then Execute() can't exit as True if the user enters a non-existent file.

That being said, a .PDF file is binary data, you can't load it into a TMemo, which works only with textual data.

Instead, load the file into a TFileStream or TMemorySteam, and then pass that to the TStream overload of Base64.Encode(), eg:

procedure TForm1.Button1Click(Sender: TObject);
var
  Input: TFileStream;
  //Input: TMemoryStream;
  Output: TStringStream;
begin
  try
    if OpenDialog1.Execute then
    begin
      Input := TFileStream.Create(OpenDialog1.FileName, fmOpenRead or fShareDenyWrite);
      // Input := TMemoryStream.Create;
      try
        //Input.LoadFromFile(OpenDialog1.FileName);
        Output := TStringStream.Create;
        try
          TNetEncoding.Base64.Encode(Input, Output);
          Memo1.Lines.Text := Output.DataString;
        finally
          Output.Free;
        end;
      finally
        Input.Free;
      end;
    end;
  except
    ShowMessage('error');
  end;
end;

Alternatively, use TMemoryStream or TFile.ReadAllBytes() with Base64.EncodeBytesToString(), eg:

procedure TForm1.Button1Click(Sender: TObject);
var
  Input: TMemoryStream;
begin
  try
    if OpenDialog1.Execute then
    begin
      Input := TMemoryStream.Create;
      try
        Input.LoadFromFile(OpenDialog1.FileName);
        Memo1.Lines.Text := TNetEncoding.Base64.EncodeBytesToString(Input.Memory, Input.Size);
      finally
        Input.Free;
      end;
    end;
  except
    ShowMessage('error');
  end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
  try
    if OpenDialog1.Execute then
      Memo1.Lines.Text := TNetEncoding.Base64.EncodeBytesToString(TFile.ReadAllBytes(OpenDialog1.FileName));
  except
    ShowMessage('error');
  end;
end;