How to retrieve a file from Internet via HTTP?

后端 未结 6 2114
天命终不由人
天命终不由人 2020-12-30 17:46

I want to download a file from Internet and InternetReadFile seem a good and easy solution at the first glance. Actually, too good to be true. Indeed, digging a bit I have s

6条回答
  •  时光说笑
    2020-12-30 18:14

    Instead of fiddling with the WinAPI, the ExtActns unit provides just what you need for downloading to a file.

    procedure TMainForm.DownloadFile(URL: string; Dest: string); 
    var 
      dl: TDownloadURL; 
    begin 
      dl := TDownloadURL.Create(self); 
      try 
        dl.URL := URL; 
        dl.FileName := Dest; 
        dl.ExecuteTarget(nil); //this downloads the file 
        dl.Free; 
      except 
        dl.Free; 
      end; 
    end; 
    

    Under the hood, it uses URLDownloadToFile from the URLMon library - which is part of IE, and therefore part of Windows.

    TDownloadURL doesn't handle any timeout for you - it doesn't look like such a thing is supported in URLMon at all, although there could be some default timeout that causes the call to fail - but you could use the OnProgress event on TDownloadURL to get notified when something happens, and then do something in another thread if it's been too long since the last callback.

提交回复
热议问题