从触发器下载delphi中的文件并捕获文件名

lou*_*zee 2 delphi http

我有一个网站的网址.它看起来像这样:http://www.example.com/downloads/file/4789/download

我想将文件保存到我的系统,但我不知道如何在我的示例中获取由URL触发的下载文件名.有些文件是pdf,其他文件是doc和rtf等.

如果有人可以请我指出文件名问题的方向以及使用哪些组件,我将非常感激.

RRU*_*RUZ 6

要从URL获取文件名,您可以检索HEAD信息并检查Content Disposition标头字段.对于此任务,您可以使用TIdHTTP indy组件.如果内容处置没有文件名,您可以尝试解析该URL.

试试这个样本.

{$APPTYPE CONSOLE}

{$R *.res}

uses
  IdURI,
  IdHttp,
  SysUtils;

function GetRemoteFileName (const URI: string) : string;
var
  LHttp: TIdHTTP;
begin
  LHttp := TIdHTTP.Create(nil);
  try
    LHttp.Head(URI);
    Result:= LHTTP.Response.RawHeaders.Params['Content-Disposition', 'filename'];
    if Result = '' then
     with TIdURI.Create(URI) do
      try
       Result := Document;
      finally
       Free;
      end;
  finally
    LHttp.Free;
  end;
end;

begin
  try
    Writeln(GetRemoteFileName('http://dl.dropbox.com/u/12733424/Blog/Delphi%20Wmi%20Code%20Creator/Setup_WmiDelphiCodeCreator.exe'));
    Writeln(GetRemoteFileName('http://studiostyl.es/settings/downloadScheme/1305'));

  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用 Indy 的 `ExtractHeaderSubItem()` 函数,而不是手动解析标题:`Result := ExtractHeaderSubItem(LHTTP.Response.ContentDisposition, 'filename', QuoteHTTP);` 或其 `TIdHeaderList.Params[]` 属性: `结果:= LHTTP.Response.RawHeaders.Params['Content-Disposition', 'filename'];`。如果你回退到`TIdURI`,使用它的`Document` 属性:`with TIdURI.Create(URI) do try Result := Document; 终于自由了;结束;` (2认同)