Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an image from a Delphi REST server and show it in a browser

When you return an image using a file stream object in a Delphi rest server, it will not display in a browser. Here is an example method that returns an image:

function TServerClass.Image: TFileStream;
begin
  Result := TFileStream.Create('pathtofile\image.png', fmOpenRead or fmShareDenyNone);
end;
like image 945
Anders E. Andersen Avatar asked Dec 14 '12 13:12

Anders E. Andersen


1 Answers

The problem is that Delphi REST server always sets the content type to text/html. This confuses the browser when you send other types of content. It is a bug, since most responses are json, which means the most sensible default content type should be application/json.

Fortunately there is a way to override the content type from within the server method.

You need to add Data.DBXPlatform to the uses list of your implementation.

This unit contains the function GetInvocationMetadata, which gives access to the response that is being build. It returns a TDSInvocationMetadata object which among varius other useful properties has the ResponseContentType property.

Setting this property overrides the Content-Type header that the method returns in the http response.

The given example becomes:

function TServerClass.Image: TFileStream;
begin
  Result := TFileStream.Create('pathtofile\image.png', fmOpenRead or fmShareDenyNone);
  GetInvocationMetadata.ResponseContentType := 'image/png';
end;

Now the result image will be displayed properly in the browser.

like image 159
Anders E. Andersen Avatar answered Nov 10 '22 14:11

Anders E. Andersen