简体   繁体   中英

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM