5

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!

TLama
  • 75,147
  • 17
  • 214
  • 392
Red October
  • 689
  • 2
  • 12
  • 31
  • 3
    The easiest option is to just use a `TFileStream` instead of a `TMemoryStream`, which would write to disk directly as the file is downloaded. `IdHTTP.Get` just asks for a `TStream`, which means you can provide any type of stream to it. – Ken White Mar 13 '13 at 11:26
  • 1
    It's like @Ken says, simply replace `TMemoryStream` with the `TFileStream`. And anyway, don't forget to ensecure the stream to be released by using `try..finally` block. Your code might be finally modified to [`something like this`](http://pastebin.com/GLVEKgLv). – TLama Mar 13 '13 at 12:20

1 Answers1

13

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.

TLama
  • 75,147
  • 17
  • 214
  • 392
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
  • 7
    I would go a step further by using an extra `try/except` to delete the file after calling `s.Free()` if `Get()` failed. With the code you showed, the file is not deleted if the download fails. Unless you want to support resuming broken downloads, in which case don't delete the file. – Remy Lebeau Mar 13 '13 at 16:50