筆者最近開發(fā)的系統(tǒng)中需要寫一個下載文件的功能。以前用BCB調(diào)用API寫的很煩瑣,忽然想起有一個API就可以搞定了,于是一大早就來搜索。這個API就是UrlDownloadToFile。不僅如此,Delphi的一些控件也可以輕松實現(xiàn)下載,如NMHTTP,指定NMHTTP1.InputFileMode := ture; 指定Body為本地文件名,指定Get就可以下載了。下面是詳細代碼,均出自CSDN。我把它們都整理到這兒,讓大家方便查閱。
uses UrlMon;
function DownloadFile(Source, Dest:
string): Boolean;
begin
try
Result := UrlDownloadToFile(nil,
PChar(source), PChar(Dest), 0, nil) = 0;
except
Result := False;
end;
end;
if DownloadFile('http:
//www.borland.com/delphi6.zip, 'c:\kylix.zip') then
ShowMessage('Download succesful')
else ShowMessage('Download unsuccesful')
========================
例程:
Uses URLMon, ShellApi;
function DownloadFile(SourceFile, DestFile: string):
Boolean;
begin
try
Result := UrlDownloadToFile(nil, PChar(SourceFile),
PChar(DestFile), 0, nil) = 0;
except
Result := False;
end;
end;
procedure TForm1.Button1.Click(Sender: TObject);
const
// URL Location
SourceFile := '/ncre/Files/2008-6/18/923232500.gif';
// Where to save the file
DestFile := 'c:\temp\google-image.gif';
begin
if DownloadFile(SourceFile, DestFile) then
begin
ShowMessage('Download succesful!');
// Show downloaded image in your browser
ShellExecute(Application.Handle,PChar('open'),PChar(DestFile),
PChar(''),nil,SW_NORMAL)
end
else
ShowMessage('Error while downloading ' + SourceFile)
end;
uses UrlMon;
function DownloadFile(Source, Dest:
string): Boolean;
begin
try
Result := UrlDownloadToFile(nil,
PChar(source), PChar(Dest), 0, nil) = 0;
except
Result := False;
end;
end;
if DownloadFile('http:
//www.borland.com/delphi6.zip, 'c:\kylix.zip') then
ShowMessage('Download succesful')
else ShowMessage('Download unsuccesful')
========================
例程:
Uses URLMon, ShellApi;
function DownloadFile(SourceFile, DestFile: string):
Boolean;
begin
try
Result := UrlDownloadToFile(nil, PChar(SourceFile),
PChar(DestFile), 0, nil) = 0;
except
Result := False;
end;
end;
procedure TForm1.Button1.Click(Sender: TObject);
const
// URL Location
SourceFile := '/ncre/Files/2008-6/18/923232500.gif';
// Where to save the file
DestFile := 'c:\temp\google-image.gif';
begin
if DownloadFile(SourceFile, DestFile) then
begin
ShowMessage('Download succesful!');
// Show downloaded image in your browser
ShellExecute(Application.Handle,PChar('open'),PChar(DestFile),
PChar(''),nil,SW_NORMAL)
end
else
ShowMessage('Error while downloading ' + SourceFile)
end;