Delphi实现文件下载UrlDownloadToFile


本文整理自网络,侵删。

 UrlDownloadToFile是一个非常不错的函数,我们可以用它来下载各种格式的图片、音乐、文件等等。
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.Button1Click(Sender: TObject);
const
// URL Location
SourceFile:='http://www.3k2.cn/images/tips.gif';
// Where to save the file
DestFile := 'c:\3k2.gif';
begin
if DownloadFile(SourceFile, DestFile) then
begin
ShowMessage('下载成功!');
// Show downloaded image in your browser
ShellExecute(Application.Handle,PChar('open'),PChar(DestFile),PChar(''),nil,SW_NORMAL)
end
else
ShowMessage(SourceFile+'下载出错!')
end;

如果涉及批量下载,那么在上例中Button1Click我们可以这样写:
procedure TForm1.Button1Click(Sender: TObject);
//---自己定义一个URL List和文件命名的List---//
begin
if DownloadFile(URLList, FileName) then
begin
ShowMessage('下载成功!');
ShellExecute(Application.Handle,PChar('open'),PChar('路径'+FileName+'.exe'),PChar(''),nil,SW_NORMAL) //这句用不上,就闪掉,只做下载测试用。
end
else
ShowMessage(URLList+'下载出错!')
end;

这个函数如果在缓存目录中有文件的话,就不会从新下载网络上的文件.解决得办法是使用api函数DeleteUrlCacheEntry('刚才下载的网址')来清除缓存文件记录

如果要控制下载进度,还要实现IBindStatusCallback接口,至于具体的操作方法.网上有相关的例程

相关阅读 >>

Delphi编写的一款锁屏小工具

Delphi xe中 exit 的新用法

Delphi 中相对路径与绝对路径函数

Delphi隐藏系统托盘tray图标

Delphi判断驱动器类型

Delphi窗体自适应分辨率

Delphi windows 编程[7] - wm_create 消息

Delphi incyear、incmonth、incweek、incday、inchour、incminute、incsecond、incmillisecond �c 增时

pchar和array [0..255] of char的区别

Delphi 流与字符串

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...