谷歌搜索显示了一些关于如何在Delphi中下载文件的示例,但大多数都是错误的,有一半的时间根据我的经验不起作用。
我正在寻找一个简单的强大解决方案,它可以让我下载一个exe(用于更新我的应用程序),并将保持当前更新线程的执行,直到下载完成或错误输出。该进程已经过线程化,因此下载代码应该执行直到完成(希望如此)。
这是两个实现,两者看起来都非常复杂
1. http://www.scalabium.com/faq/dct0116.htm
2. http://delphi.about.com/od/internetintranet/a/get_file_net.htm
答案 0 :(得分:16)
为什么不利用indy。如果你使用TIdHTTP简单
procedure DownloadFile;
var
IdHTTP1: TIdHTTP;
Stream: TMemoryStream;
Url, FileName: String;
begin
Url := 'http://www.rejbrand.se';
Filename := 'download.htm';
IdHTTP1 := TIdHTTP.Create(Self);
Stream := TMemoryStream.Create;
try
IdHTTP1.Get(Url, Stream);
Stream.SaveToFile(FileName);
finally
Stream.Free;
IdHTTP1.Free;
end;
end;
您甚至可以使用OnWork和OnWorkBegin事件添加进度条
procedure IdHTTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode;AWorkCountMax: Int64);
begin
ProgressBar.Max := AWorkCountMax;
ProgressBar.Position := 0;
end;
procedure IdHTTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
begin
ProgressBar.Position := AWorkCount;
end;
我不确定这些事件是否会在主线程的上下文中触发,因此可能必须使用tidnotify组件对VCL组件进行任何更新以避免线程问题。也许别人可以检查一下。
答案 1 :(得分:15)
第二种方法是使用WinINet(Windows API的一部分)使用Internet资源的标准方法。我经常使用它,它一直很好用。我从未尝试过的第一种方法。 (两者都不“非常复杂”。使用Windows API时总会有一些额外的步骤。)
如果您想要一种非常简单的方法,只需拨打UrlMon.URLDownloadToFile
即可。
示例:
URLDownloadToFile(nil,
'http://www.rejbrand.se',
PChar(ExtractFilePath(Application.ExeName) + 'download.htm'),
0,
nil);
答案 2 :(得分:0)
对于拥有更高版本 delphi 的人,您可以使用这个:
SELECT
o.orderid AS id,
sd.datestart AS startdate,
sd.dateend AS enddate,
o.comment AS comment,
o.productname AS name,
o.suspended AS sus,
o.voided AS void,
o.invoice_number AS inumber,
GROUP_CONCAT(js.title) AS sections,
GROUP_CONCAT(js.sectionid) AS sectionid,
js.is_science_education AS isse,
o.amount AS amount,
js.isbundle,
o.addedbyuserid,
(SELECT
COUNT(*)
FROM
institutiontoorder AS ito2
WHERE
orderid = ito.orderid) AS multiple
FROM
institutiontoorder AS ito
LEFT JOIN
subscribedates AS sd ON ito.orderid = sd.orderid
LEFT JOIN
ordertosection AS ots ON ots.orderid = ito.orderid
LEFT JOIN
orders AS o ON o.orderid = ito.orderid
LEFT JOIN
institutions AS i ON i.institutionid = ito.institutionid
JOIN
journalsections AS js ON js.sectionid = ots.sectionid
WHERE
ito.institutionid = '1419'
AND o.voided != 1
AND o.suspended != 1
AND (dateend >= NOW())
GROUP BY o.orderid
ORDER BY o.orderid DESC;
答案 3 :(得分:-2)
使用URLMon。
errcode := URLMon.URLDownloadToFile(nil,
PChar('http://www.vbforums.com/showthread.php?345726-DELPHI-Download-Files'),
PChar( 'a:\download.htm'),
0,
nil);
if errcode > 0 then
showmessage('Error while downloading: ' + inttostr(errcode));