从Delphi REST服务器返回图像,并在浏览器中显示 [英] Return an image from a Delphi REST server and show it in a browser

查看:673
本文介绍了从Delphi REST服务器返回图像,并在浏览器中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您使用Delphi休息服务器中的文件流对象返回图像时,它不会显示在浏览器中。这是一个返回图像的示例方法:

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;


推荐答案

问题是Delphi REST服务器总是设置内容键入text / html。当您发送其他类型的内容时,这会混淆浏览器。这是一个错误,因为大多数响应是json,这意味着最合理的默认内容类型应该是application / json。

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.

您需要将Data.DBXPlatform添加到实现的使用列表中。

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

该单位包含 GetInvocationMetadata 的功能,该功能可以访问正在构建的响应。它返回一个 TDSInvocationMetadata 对象,其中有其他有用的属性之间具有ResponseContentType 属性。

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.

设置此属性覆盖该方法在http响应中返回的Content-Type头。

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

给定的示例变为:

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.

这篇关于从Delphi REST服务器返回图像,并在浏览器中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆