【发布时间】:2012-02-28 06:30:30
【问题描述】:
我从第三方网站获得以下来源,解释如何使用 WinInet 从 Internet 下载文件。我对 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;
【问题讨论】:
-
我实现了这样一个功能,发现使用 WinInet 会导致我的应用程序中发生可怕的“超时错误”。通常需要 100 毫秒的 Http-Head 请求需要 15 秒才能返回。在某些版本的 Windows/WinInet 上从 Delphi 调用 WinInet 是一个已知问题。我提到这一点,以防您以后遇到这种奇怪的故障。如果您可以在这里使用 Indy 或其他非 WinInet(例如 WinHttp),请考虑一下! :-)
-
..It is a known problem in calling WinInet from Delphi on some versions of Windows/WinInet@WarrenP 我在使用 Delphi 的 WinInet 时从未遇到过这个问题。你能指出一些关于这个主题的文档或链接吗? -
这里有一个链接:jgobserve.blogspot.com/2009/03/… -- 我的观察是,问题不限于当底层网络出现故障时,你会等待很长时间。有时一切看起来都很好,除了 winInet 有我无法解释的超时。我在 Python 中编写的代码,或者在 Delphi 中使用 INDY 或 ICS 编写的代码没有表现出相同的失败模式。
-
我在一年半前发布了这个,当我阅读我的代码时,我意识到我没有使用同步线程保护事件。过去一年我所有最新的线程我都仔细设计了关键部分,但是当我不知道如何使任何东西成为线程安全的时候,这又回来了。
标签: delphi download delphi-xe2 wininet progressive-download