使用INDY检测远程服务器上文件的MIME类型 [英] Detecting the Mime-Type of a file on a remote server with INDY
问题描述
我一直在使用Synapse库从互联网上下载文件,但是最近我将应用程序转换为使用INDY,而我却错过了Synapse库中更好的功能之一,即可以轻松获取Mime的功能. -在将文件保存到本地计算机之前从服务器下载的文件的类型. INDY是否具有此功能,如果可以,我该如何访问它?
I have been using the Synapse library to download files from the internet, but I have recently converted my application to use INDY instead and I am missing one of the nicer features in the Synapse library which is the ability to easily get the Mime-Type of a file that I was downloading from a server before saving it to my local machine. Does INDY have this feature and if so how do I go about accessing it?
推荐答案
您可以发出HTTP HEAD
请求并检查Content-Type
标头.实际GET
文件(下载)之前:
You can issue an HTTP HEAD
request and check the Content-Type
header. Before you actually GET
the file (download) :
procedure TForm1.Button1Click(Sender: TObject);
var
Url: string;
Http: TIdHTTP;
begin
Url := 'http://yoursite.com/yourfile.png';
Http := TIdHTTP.Create(nil);
try
Http.Head(Url);
ShowMessage(Http.Response.ContentType); // "image/png"
finally
Http.Free;
end;
end;
您收到的ContentType
取决于Web服务器的实现,并且不能保证每台服务器上的ContentType
都相同.
The ContentType
you receive back depends on the web server implementation and is not guaranteed to be the same on each and every server.
另一种选择是实际GET
文件并将其内容保存到诸如TMemoryStream
之类的内存流中(而不是保存到本地文件中). Indy提供了重载:
The other option, is to actually GET
the file and save it's content to a memory stream such as TMemoryStream
(not to a local file). Indy provides an overload:
Http.Get(Url, AStream);
然后您检查Http.Response.ContentType
,并将流保存到文件:AStream.SaveToFile
.
Then you check the Http.Response.ContentType
, and Save the stream to file: AStream.SaveToFile
.
不确定此处的相关性,但还要注意,Indy也可以返回/猜测本地文件的mime类型(给定文件扩展名).使用GetMIMETypeFromFile
(使用IdGlobalProtocols
).另请参见此处.
Not sure about the relevancy here, but note also that Indy can return/guess the mime type of a local file as well (given a file extension). with GetMIMETypeFromFile
(uses IdGlobalProtocols
). See also here.
这篇关于使用INDY检测远程服务器上文件的MIME类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!