Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I download a huge file via TIdHTTP?

I use this code to download small files:

Var
 ms:TMemoryStream;
begin
  ms:=TMemoryStream.Create;
  Idhttp1.get('http://mydomain.com/myfile.zip',ms);
  ms.SaveToFile('myfile.zip');
  ms.Free;
end;

But file is saved in RAM before storing to disk, so it may be difficult to download files >1Gb, for example. Is there a way to download a file by its parts? Or do I need to use the WinInet? Thanks in advance!

like image 893
Red October Avatar asked Dec 12 '22 16:12

Red October


1 Answers

TMemoryStream provides an in-memory buffer, so if you download into one, you need to have enough memory to hold everything you receive. It's not the only kind of stream, though. You can pass the Get method any kind of stream you want, including one that writes its contents to disk as it receives it. Use TFileStream, for example.

var
  s: TStream;

s := TFileStream.Create('myfile.zip', fmCreate);
try
  IdHttp1.Get(..., s);
finally
  s.Free;
end;

Anywhere you call LoadFromFile or SaveToFile on a TMemoryStream, it's possible that TFileStream is a better choice.

like image 169
Rob Kennedy Avatar answered Dec 21 '22 23:12

Rob Kennedy