注意:我只想使用wininet,而不是urlmon-urldownloadtofile。
好吧,我有以下代码可以在 XE2 中完美地下载文件:
procedure DownloadFile(URL: string; Path: string);
const
BLOCK_SIZE = 1024;
var
InetHandle: Pointer;
URLHandle: Pointer;
FileHandle: Cardinal;
BytesRead: Cardinal;
DownloadBuffer: Pointer;
Buffer: array [1 .. BLOCK_SIZE] of byte;
BytesWritten: Cardinal;
begin
InetHandle := InternetOpen(PWideChar(URL), 0, 0, 0, 0);
URLHandle := InternetOpenUrl(InetHandle, PWideChar(URL), 0, 0, 0, 0);
FileHandle := CreateFile(PWideChar(Path), GENERIC_WRITE, FILE_SHARE_WRITE, 0,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);
DownloadBuffer := @Buffer;
repeat
InternetReadFile(URLHandle, DownloadBuffer, BLOCK_SIZE, BytesRead);
if not WriteFile(FileHandle, DownloadBuffer, BytesRead, BytesWritten, 0) or
(BytesWritten <> BytesRead) then
RaiseLastOSError;
until BytesRead < BLOCK_SIZE;
CloseHandle(FileHandle);
InternetCloseHandle(URLHandle);
InternetCloseHandle(InetHandle);
end;
上述代码的功劳归于 jachguate。他编辑了我的代码以更正它,我为此感谢他。
现在,这段代码只能在 Delphi XE2 下正常工作。我尝试在 Delphi 7 下使用它,但它无法正常工作。似乎多次将相同的“行”或“字节序列”存储到文件中。
以下是我尝试在 Delphi 7 中使用的上述代码的两种改型——它们都不能正常工作。
procedure DownloadFile(URL: string; Path: string);
const
BLOCK_SIZE = 1024;
var
InetHandle: Pointer;
URLHandle: Pointer;
FileHandle: Cardinal;
BytesRead: Cardinal;
DownloadBuffer: Pointer;
Buffer: array [1 .. BLOCK_SIZE] of byte;
BytesWritten: Cardinal;
begin
InetHandle := InternetOpen(PChar(URL), 0, 0, 0, 0);
URLHandle := InternetOpenUrl(InetHandle, PChar(URL), 0, 0, 0, 0);
FileHandle := CreateFile(PChar(Path), GENERIC_WRITE, FILE_SHARE_WRITE, 0,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);
DownloadBuffer := @Buffer;
repeat
InternetReadFile(URLHandle, DownloadBuffer, BLOCK_SIZE, BytesRead);
if not WriteFile(FileHandle, DownloadBuffer, BytesRead, BytesWritten, 0) or
(BytesWritten <> BytesRead) then
RaiseLastOSError;
until BytesRead < BLOCK_SIZE;
CloseHandle(FileHandle);
InternetCloseHandle(URLHandle);
InternetCloseHandle(InetHandle);
end;
procedure DownloadFile(URL: string; Path: string);
const
BLOCK_SIZE = 1024;
var
InetHandle: Pointer;
URLHandle: Pointer;
FileHandle: Cardinal;
BytesRead: Cardinal;
DownloadBuffer: Pointer;
Buffer: array [1 .. BLOCK_SIZE] of byte;
BytesWritten: Cardinal;
begin
InetHandle := InternetOpen(PAnsiChar(URL), 0, 0, 0, 0);
URLHandle := InternetOpenUrl(InetHandle, PAnsiChar(URL), 0, 0, 0, 0);
FileHandle := CreateFile(PAnsiChar(Path), GENERIC_WRITE, FILE_SHARE_WRITE, 0,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);
DownloadBuffer := @Buffer;
repeat
InternetReadFile(URLHandle, DownloadBuffer, BLOCK_SIZE, BytesRead);
if not WriteFile(FileHandle, DownloadBuffer, BytesRead, BytesWritten, 0) or
(BytesWritten <> BytesRead) then
RaiseLastOSError;
until BytesRead < BLOCK_SIZE;
CloseHandle(FileHandle);
InternetCloseHandle(URLHandle);
InternetCloseHandle(InetHandle);
end;
唯一编辑的是数据类型转换。使用示例一“PChar”,使用示例二“PAnsiChar”。