加入收藏  广告服务  关于我们
 2003-9-16

[源码]使用WinINet进行HTTP上传、下载文件(函数)

发表:刀剑如梦   阅读:次  关键字:不详   字体:[ ]

//为支持本站,特地帖上两段代码,相信大家在很多情况下都可能用得上。(基本原创 :) )
uses
WinINet;

//下载指定URL的文件,以字符串方式返回
function UrlGetStr(const URL: string): string;
const
Agent = 'Internet Explorer 6.0';
var
hFile, HInet: HINTERNET;
Buffer: array[0..32767] of Char;
BufRead: Cardinal;
BufSize: Cardinal;
begin
HInet := InternetOpen(PChar(Agent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if Assigned(HInet) then
try
hFile := InternetOpenUrl(HInet, PChar(URL), nil, 0, INTERNET_FLAG_RELOAD +
INTERNET_FLAG_NO_CACHE_WRITE + INTERNET_FLAG_EXISTING_CONNECT +
INTERNET_FLAG_NO_COOKIES, 0);
if Assigned(hFile) then
try
BufSize := SizeOf(Buffer);
with TStringStream.Create('') do
try
while InternetReadFile(hFile, @Buffer, BufSize, BufRead) and (BufRead > 0) do
Write(Buffer, BufRead);
Result := DataString;
finally
Free;
end;
finally
InternetCloseHandle(hFile);
end;
finally
InternetCloseHandle(hinet);
end;
end;

//上传本地文件到远程HTTP服务器的指定目录
function HttpSendFile(const ALocalFile, ARemoteServer, ARemoteFile, AUser, APass: string): string;
const
cBuffsize = 1024 * 64;
var
HttpNet, HttpConnect, HttpRequest: HINTERNET;
BufferIn: INTERNET_BUFFERS;
hfile&: THandle;
readInF: DWORD;
oBytesWritten: DWORD;
Count: DWORD;
pBuffer: string;
begin
HttpNet := InternetOpen(PChar(ARemoteServer), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if HttpNet = nil then
RaiseLastOSError;
try
HttpConnect := InternetConnect(HttpNet, PChar(ARemoteServer), 0, PChar(AUser),
PChar(APass), INTERNET_SERVICE_HTTP, 0, 0);
if HttpConnect = nil then
RaiseLastOSError;
try
HttpRequest := HttpOpenRequest(HttpConnect, 'PUT', PChar(ARemoteFile),
nil, nil, nil, 0, 0);
if HttpRequest = nil then
RaiseLastOSError;
try
hFile := CreateFile(PChar(ALocalFile), GENERIC_READ, FILE_SHARE_READ,
nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if hFile = 0 then
RaiseLastOSError;
try
FillChar(BufferIn, SizeOf(BufferIn), 0);
BufferIn.dwStructSize := SizeOf(BufferIn);
BufferIn.dwBufferLength := cBuffsize;
BufferIn.dwBufferTotal := GetFileSize(hFile, nil);
HttpSendRequestEx(HttpRequest, @BufferIn, nil, HSR_INITIATE, 0);

ReadInF := 0;
repeat
SetLength(pBuffer, cBuffsize);
ReadFile(hFile, Pointer(pBuffer)^, cBuffsize, Count, nil);
ReadInF := ReadInF + Count;
InternetWriteFile(httpRequest, Pointer(pBuffer), Count, oBytesWritten);
until ReadInF = BufferIn.dwBufferTotal;

finally
CloseHandle(hFile);
end;
finally
HttpEndRequest(HttpRequest, nil, 0, 0);
InternetCloseHandle(HttpRequest);
end;
finally
InternetCloseHandle(HttpConnect);
end;
finally
InternetCloseHandle(HttpNet);
end;
end;

 热门文章
 推荐信息