用Delphi实现文件下载的几种方法

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 yeqiufeng 的 blog

笔者最近开发的系统中需要写一个下载文件的功能。以前用bcb调用api写的很烦琐,忽然想起有一个api就可以搞定了,于是一大早就来搜索。这个api就是urldownloadtofile。不仅如此,delphi的一些控件也可以轻松实现下载,如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 := 'http://www.google.com/intl/de/images/home_title.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;

=================

加入如下代码:

nmhttp1.inputfilemode := ture;
nmhttp1.body := '本地文件名';
nmhttp1.header := 'head.txt';
nmhttp1.outputfilemode := false;
nmhttp1.reportlevel := status_basic;
nmhttp1.proxy := '代理服务器的ip地址';
nmhttp1.proxyport := '代理服务器的端口号';
with nmhttp1.headerinfo do

begin
cookie := '';
localmailaddress := '';
localprogram := '';
referer := '';
userid := '用户名称';
password := '用户口令';
end;

nmhttp1.get(‘http://www.abcdefg.com/software/a.zip’);

试试吧,delphi的目录中有tnmhttp控件的例子。nt4+,win95+,ie3+,你可以用url moniker的功能。

uses urlmon;

...

olecheck(urldownloadtofile(nil,'url','filename',0,nil));

其中最后一个参数你还可以传入一个ibindstatuscallback的实现以跟踪下载进度或控制中止下载。简单的场合一句话就搞定了。

--回复得分 0--

btw, url moniker封装了大多数url,而不是像nmhttp那样封装协议,因此你可以用urldownloadtofile下载http,ftp甚至本地文件和局域网文件,还有其他的custom moniker,比如msitstore(msdn library的文档moniker实现)。

============
用idhttp控件吧!
var
  downloadfile:tfilestream;
beginio
  downloadfile:=tfilestream.create('c:\aa.rar',fmcreate);
  idhttp1.get('http://www.sina.com.cn/download/aa.rar',downloadfile);
  downloadfile.free;
end;

//---------------------------

程序结束

本文关键:Delphi,文件,下载,HTTP,NMHTTP,IdHTTP,UrlDownloadToFile
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top