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;
First off, rather than using
FileExists()afterTOpenDialog.Execute()returnTrue, you should instead enableTOpenDialog'sofPathMustExistandofFileMustExistoptions, thenExecute()can't exit asTrueif the user enters a non-existent file.That being said, a
.PDFfile is binary data, you can't load it into aTMemo, which works only with textual data.Instead, load the file into a
TFileStreamorTMemorySteam, and then pass that to theTStreamoverload ofBase64.Encode(), eg:Alternatively, use
TMemoryStreamorTFile.ReadAllBytes()withBase64.EncodeBytesToString(), eg: