Stefan De Beer
Stefan De Beer

Reputation: 23

TClientDataSet read Binary field to TStream

i have tried this every way that I possible can, but cannot seem to resolve this. I am working with DBExress in Delphi XE3 writing a REST DataSnap Server.

I have data stored in MSQL in a Binary(384) field and Binary is as far as I know that same as a BLOB/Image field as it is all Binary data.

When trying to stream this data to a TStream I receive an exception error and have tried the following

var
STemplate : TStream;
begin
......
Template := TBlobField.Create(cdsBSUserTemplates.FieldByName('bTemplate'));
TBlobField(cdsBSUserTemplates.FieldByName('bTemplate')).SaveToStream(STemplate); //exception
......
end;

and I have tried

var
STemplate : TStream;
begin
......
Template := TBlobField.Create(cdsBSUserTemplates.FieldByName('bTemplate'));
STemplate := cdsBSUserTemplates.CreateBlobStream(Template, bmRead); //exception
......
end;

I can return the value .AsString, but it is Bytes and then I need to try and fix what I have read from that field.

Any idea what else I can try?

Upvotes: 1

Views: 1580

Answers (1)

Ken White
Ken White

Reputation: 125620

You're working much too hard. :-)

You need to properly create the stream, and then just let the field write to it.

var
  Output: TMemoryStream;
  Fld: TBlobField;
begin
  // Use of variable makes it more readable
  Fld := cdsBSUserTemplates.FieldByName('bTemplate') as TBlobField;

  Output := TMemoryStream.Create;
  try
    Fld.SaveToStream(Output);
    Output.Position := 0;
    // Do whatever with the output stream
  finally
    Output.Free;
  end;
end;

After your comment that you might not be using a TBlobField (which would have been nice to know before I posted my answer), you can try this instead (untested, because I clearly don't have your data):

var
  Output: TMemoryStream;
  Fld: TField;
  Bytes: TArray<Byte>;
begin
  Fld := ADOQuery1.FieldByName('bTemplate');
  Output := TMemoryStream.Create;
  try
    if Fld.IsBlob then
      TBlobField(Fld).SaveToStream(Output)
    else
    begin
      Fld.GetData(Bytes);
      Output.WriteData(Bytes, Length(Bytes));
    end;
    // Do whatever with output
  finally
    Output.Free;
  end;
end;

Upvotes: 2

Related Questions