使用WinInet在下载文件之前确定文件的总大小

9
我从第三方网站获取了以下源代码,它解释了如何使用WinInet从互联网下载文件。我对API不太熟悉,我看了一下WinInet单元,但没有看到像我需要的API调用。
我的目标是添加报告下载进度的功能。我已经在一个TThread中包装了这个过程,一切都很顺利。然而,只有一个缺失的部分:在下载之前找到源文件的总大小。
请看下面我有一个注释 "//HOW TO GET TOTAL SIZE?"。这是我需要在开始下载之前找出文件的总大小的地方。我该怎么做?因为这段代码似乎直到下载完成后才知道文件的大小,这使得这个补充无关紧要。
procedure TInetThread.Execute;
const
  BufferSize = 1024;
var
  hSession, hURL: HInternet;
  Buffer: array[1..BufferSize] of Byte;
  BufferLen: DWORD;
  f: File;
  S: Bool;
  D: Integer;
  T: Integer;
  procedure DoWork(const Amt: Integer);
  begin
    if assigned(FOnWork) then
      FOnWork(Self, FSource, FDest, Amt, T);
  end;
begin
  S:= False;
  try
    try
      if not DirectoryExists(ExtractFilePath(FDest)) then begin
        ForceDirectories(ExtractFilePath(FDest));
      end;
      hSession:= InternetOpen(PChar(FAppName), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
      try
        hURL:= InternetOpenURL(hSession, PChar(FSource), nil, 0, 0, 0);
        try
          AssignFile(f, FDest);
          Rewrite(f, 1);
          T:= 0; //HOW TO GET TOTAL SIZE?
          D:= 0;
          DoWork(D);
          repeat
            InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen);
            BlockWrite(f, Buffer, BufferLen);
            D:= D + BufferLen;
            DoWork(D);
          until BufferLen = 0;
          CloseFile(f);
          S:= True;
        finally
          InternetCloseHandle(hURL);
        end
      finally
        InternetCloseHandle(hSession);
      end;
    except
      on e: exception do begin
        S:= False;
      end;
    end;
  finally
    if assigned(FOnComplete) then
      FOnComplete(Self, FSource, FDest, S);
  end;
end;

3
我实现了这样一个功能,发现使用WinInet会在我的应用程序中出现可怕的“超时错误”。通常只需要100毫秒的Http-Head请求,却需要长达15秒才能返回。这在某些版本的Windows/WinInet上调用Delphi时是个已知的问题。我提到这一点是为了防止您以后遇到这种奇怪的故障。如果可以使用Indy或其他非WinInet的工具(如WinHttp),请考虑使用! :-) - Warren P
@WarrenP 在某些版本的Windows/WinInet上从Delphi调用WinInet是一个已知的问题。我从未在使用Delphi的WinInet时遇到过这个问题。您能否提供一些关于这个主题的文档或链接? - RRUZ
这是一个链接:http://jgobserve.blogspot.com/2009/03/wininet-timeout-issue-and-solution.html -- 我的观察是,问题不仅仅局限于当底层网络失败时会出现长时间等待的情况。有时候一切似乎都很正常,除了winInet会出现超时,我无法解释这种情况。我用Python编写的代码或使用INDY或ICS编写的Delphi代码没有展现出相同的故障模式。 - Warren P
我一年半前发布了这篇文章,当我阅读我的代码时,我意识到我没有使用同步来保护事件。在过去的一年中,我仔细设计了关键部分以确保线程安全,但那时我还不知道如何使所有内容都线程安全。 - Jerry Dodge
3个回答

18

您可以使用HEAD方法并检查Content-Length来检索远程文件的文件大小。

检查这两种方法

WinInet

如果您想执行HEAD方法,您必须使用HttpOpenRequest, HttpSendRequestHttpQueryInfo WinInet函数。

uses
 SysUtils,
 Windows,
 WinInet;

function GetWinInetError(ErrorCode:Cardinal): string;
const
   winetdll = 'wininet.dll';
var
  Len: Integer;
  Buffer: PChar;
begin
  Len := FormatMessage(
  FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM or
  FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_IGNORE_INSERTS or  FORMAT_MESSAGE_ARGUMENT_ARRAY,
  Pointer(GetModuleHandle(winetdll)), ErrorCode, 0, @Buffer, SizeOf(Buffer), nil);
  try
    while (Len > 0) and {$IFDEF UNICODE}(CharInSet(Buffer[Len - 1], [#0..#32, '.'])) {$ELSE}(Buffer[Len - 1] in [#0..#32, '.']) {$ENDIF} do Dec(Len);
    SetString(Result, Buffer, Len);
  finally
    LocalFree(HLOCAL(Buffer));
  end;
end;


procedure ParseURL(const lpszUrl: string; var Host, Resource: string);
var
  lpszScheme      : array[0..INTERNET_MAX_SCHEME_LENGTH - 1] of Char;
  lpszHostName    : array[0..INTERNET_MAX_HOST_NAME_LENGTH - 1] of Char;
  lpszUserName    : array[0..INTERNET_MAX_USER_NAME_LENGTH - 1] of Char;
  lpszPassword    : array[0..INTERNET_MAX_PASSWORD_LENGTH - 1] of Char;
  lpszUrlPath     : array[0..INTERNET_MAX_PATH_LENGTH - 1] of Char;
  lpszExtraInfo   : array[0..1024 - 1] of Char;
  lpUrlComponents : TURLComponents;
begin
  ZeroMemory(@lpszScheme, SizeOf(lpszScheme));
  ZeroMemory(@lpszHostName, SizeOf(lpszHostName));
  ZeroMemory(@lpszUserName, SizeOf(lpszUserName));
  ZeroMemory(@lpszPassword, SizeOf(lpszPassword));
  ZeroMemory(@lpszUrlPath, SizeOf(lpszUrlPath));
  ZeroMemory(@lpszExtraInfo, SizeOf(lpszExtraInfo));
  ZeroMemory(@lpUrlComponents, SizeOf(TURLComponents));

  lpUrlComponents.dwStructSize      := SizeOf(TURLComponents);
  lpUrlComponents.lpszScheme        := lpszScheme;
  lpUrlComponents.dwSchemeLength    := SizeOf(lpszScheme);
  lpUrlComponents.lpszHostName      := lpszHostName;
  lpUrlComponents.dwHostNameLength  := SizeOf(lpszHostName);
  lpUrlComponents.lpszUserName      := lpszUserName;
  lpUrlComponents.dwUserNameLength  := SizeOf(lpszUserName);
  lpUrlComponents.lpszPassword      := lpszPassword;
  lpUrlComponents.dwPasswordLength  := SizeOf(lpszPassword);
  lpUrlComponents.lpszUrlPath       := lpszUrlPath;
  lpUrlComponents.dwUrlPathLength   := SizeOf(lpszUrlPath);
  lpUrlComponents.lpszExtraInfo     := lpszExtraInfo;
  lpUrlComponents.dwExtraInfoLength := SizeOf(lpszExtraInfo);

  InternetCrackUrl(PChar(lpszUrl), Length(lpszUrl), ICU_DECODE or ICU_ESCAPE, lpUrlComponents);

  Host := lpszHostName;
  Resource := lpszUrlPath;
end;

function GetRemoteFileSize(const Url : string): Integer;
const
  sUserAgent = 'Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0) Gecko/25250101';

var
  hInet    : HINTERNET;
  hConnect : HINTERNET;
  hRequest : HINTERNET;
  lpdwBufferLength: DWORD;
  lpdwReserved    : DWORD;
  ServerName: string;
  Resource: string;
  ErrorCode : Cardinal;
begin
  ParseURL(Url,ServerName,Resource);
  Result:=0;

  hInet := InternetOpen(PChar(sUserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if hInet=nil then
  begin
    ErrorCode:=GetLastError;
    raise Exception.Create(Format('InternetOpen Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
  end;

  try
    hConnect := InternetConnect(hInet, PChar(ServerName), INTERNET_DEFAULT_HTTP_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 0);
    if hConnect=nil then
    begin
      ErrorCode:=GetLastError;
      raise Exception.Create(Format('InternetConnect Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
    end;

    try
      hRequest := HttpOpenRequest(hConnect, PChar('HEAD'), PChar(Resource), nil, nil, nil, 0, 0);
        if hRequest<>nil then
        begin
          try
            lpdwBufferLength:=SizeOf(Result);
            lpdwReserved    :=0;
            if not HttpSendRequest(hRequest, nil, 0, nil, 0) then
            begin
              ErrorCode:=GetLastError;
              raise Exception.Create(Format('HttpOpenRequest Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
            end;

             if not HttpQueryInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH or HTTP_QUERY_FLAG_NUMBER, @Result, lpdwBufferLength, lpdwReserved) then
             begin
              Result:=0;
              ErrorCode:=GetLastError;
              raise Exception.Create(Format('HttpQueryInfo Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
             end;
          finally
            InternetCloseHandle(hRequest);
          end;
        end
        else
        begin
          ErrorCode:=GetLastError;
          raise Exception.Create(Format('HttpOpenRequest Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)]));
        end;
    finally
      InternetCloseHandle(hConnect);
    end;
  finally
    InternetCloseHandle(hInet);
  end;

end;

Indy

同时使用 Indy 检查此代码。

function GetRemoteFilesize(const Url :string) : Integer;
var
  Http: TIdHTTP;
begin
  Http := TIdHTTP.Create(nil);
  try
    Http.Head(Url);
    result:= Http.Response.ContentLength;
  finally
    Http.Free;
  end;
end;

2
+1 分钟收到,我应该使用 Indy 代替 :D 只是为了更干净的代码。 - Jerry Dodge
3
如果你知道你将下载资源,那么你可以发送一个GET请求并从其中读取Content-Length头部来代替吗?这样可以避免额外的HTTP连接。 - Rob Kennedy
6
@RobKennedy - 是的,只要数据没有使用“Transfer-Encoding: chunked”头以块的形式发送,那么就可以使用“Content-Length”头来确定数据的总大小。如果数据使用“Transfer-Encoding: chunked”头发送,则无法使用“Content-Length”头确定总大小,直到接收到最后一块数据才能确定。 - Remy Lebeau

3

回答如何使用WinInet获取下载大小的问题。这是基于WinInet的文件下载器之一。

这是我用来获取下载大小的方法:

function TWebDownloader.GetContentLength(URLHandle: HINTERNET): Int64;
// returns the expected download size.  Returns -1 if one not provided
   var
     SBuffer: Array[1..20] of char;
     SBufferSize: Integer;
     srv: integer;
   begin
     srv := 0;
    SBufferSize := 20;
    if HttpQueryInfo(URLHandle, HTTP_QUERY_CONTENT_LENGTH, @SBuffer, SBufferSize, srv) then
       Result := StrToFloat(String(SBuffer))
    else
       Result := -1;
   end;

使用此方法需要一个打开的请求句柄,而且不需要读取任何数据。
 URLHandle := HttpOpenRequest(ConnectHandle, 'GET', Pchar(sitepath), nil,
                  nil, nil, INTERNET_FLAG_NO_CACHE_WRITE, 0);
 ...
 DownloadSize := GetContentLength(URLHandle);

HTH


+1 很棒的东西,而且代码只有另一个答案的1/6 :) 顺便问一下,你那个庞大的下载器项目进展如何了? - Jerry Dodge
我真的很好奇它是如何工作的,因为条件是互斥的:a)方法是GET b)未传输请求的资源。我的猜测是当头部接收完毕时,它会关闭连接。 - OnTheFly
@JerryDodge 这个项目已经满足我的需求,我已经转向其他事情了。不过仍需要进行大量清理工作。 - Glenn1234

0

修正类型后,它看起来更好:

function GetContentLength(URLHandle:HINTERNET):Int64;
// returns the expected download size.  Returns -1 if one not provided
var
 SBufferSize, srv:Cardinal;
begin
 srv:=0;
 SBufferSize:=20;
 if Not HttpQueryInfo(URLHandle, HTTP_QUERY_CONTENT_LENGTH or HTTP_QUERY_FLAG_NUMBER, {@SBuffer} @Result, SBufferSize, srv) then Result:=-1;
end;

调用它:

{get the file handle}
hURL:=InternetOpenURL(hSession, PChar(URL), nil, 0, 0, 0);
if hURL=Nil then
begin
 InternetCloseHandle(hSession);
 ShowMessage('The link is incorrect!');
 exit;
end;
{get the file size}
filesize:=GetContentLength(hURL);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接