Downloading a file in Delphi
Why not make use of Indy? If you use the TIdHTTP
component, it's simple:
procedure TMyForm.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;
You can even add a progress bar by using the OnWork
and OnWorkBegin
events:
procedure TMyForm.IdHTTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode;AWorkCountMax: Int64);begin ProgressBar.Max := AWorkCountMax; ProgressBar.Position := 0;end;procedure TMyForm.IdHTTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);begin ProgressBar.Position := AWorkCount;end;procedure TMyForm.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.OnWorkBegin := IdHTTPWorkBegin; IdHTTP1.OnWork := IdHTTPWork; IdHTTP1.Get(Url, Stream); Stream.SaveToFile(FileName); finally Stream.Free; IdHTTP1.Free; end;end;
I'm not sure if these events fire in the context of the main thread, so any updates done to VCL components may have to be done using the TIdNotify
component to avoid threading issues. Maybe someone else can check that.
The second approach is the standard way of using Internet resources using WinINet, a part of Windows API. I have used it a lot, and it has always worked well. The first approach I have never tried. (Neither is "very complicated". There will always be a few additional steps when using the Windows API.)
If you want a very simple method, you could simply call UrlMon.URLDownloadToFile
. You will not get any fine control (at all!) about the download, but it is very simple.
Example:
URLDownloadToFile(nil, 'http://www.rejbrand.se', PChar(ExtractFilePath(Application.ExeName) + 'download.htm'), 0, nil);
For people that has later version of delphi, you can use this:
var http : TNetHTTPClient; url : string; stream: TMemoryStream;begin http := TNetHTTPClient.Create(nil); stream := TMemoryStream.Create; try url := YOUR_URL_TO_DOWNLOAD; http.Get(url, stream); stream.SaveToFile('D:\Temporary\1.zip'); finally stream.Free; http.Free; end;end;