How To…Save/Load Archives from a Database

Question

“How do I save/load archive files to and from a table in my database?”

Solution

To save a file to DB, export the archive to memory stream using the TppStreamDevice.OutputStream property, then copy that to a TBlobStream which can easily be saved to a DB.
If the archives are already saved to file, create a TFileStream and use the same technique.

Loading archives from a database can easily be done using the TppDBArchiveReader object available from the Delphi component pallet.

Download: DBArchiveReader.zip

Sample Delphi code:

procedure TForm1.TransferArchiveToBLOBField(const aName: String);
var
  lArchive: TMemoryStream;
  lArchiveDevice: TppArchiveDevice;
  lsArchive: String;
begin

  lArchive := TMemoryStream.Create;
  lArchiveDevice := TppArchiveDevice.Create(nil);

  try

    lArchiveDevice.OutputStream := lArchive;

    lArchiveDevice.Publisher := ppReport1.Publisher;

    ppReport1.PrintToDevices;

  finally
    lArchiveDevice.Free;
  end;

  tblArchive.Append;

  try
    tblArchive.FieldByName('Name').AsString := aName;
    TBlobField(tblArchive.FieldByName('Archive')).LoadFromStream(lArchive);

  except
    tblArchive.Cancel;

    raise;
  end;

  tblArchive.Post;

  lArchive.Free;

end;

procedure TForm1.btnReadArchiveClick(Sender: TObject);
begin

  FReader := TppDBArchiveReader.Create(Self);
  FReader.DatabaseSettings.DataPipeline := ppDBPipeline1;
  FReader.DatabaseSettings.NameField := 'Name';
  FReader.DatabaseSettings.BLOBField := 'Archive';

  FReader.DatabaseSettings.Name := tblArchive.FieldByName('Name').AsString;

  FReader.Print;

end;