Alberto Rossi
Alberto Rossi

Reputation: 1800

Delphi download files in a directory

I have found some solutions but they are too much sophisticated or simply they don't work. I have to download 200 pictures from a server (small pictures, about 15 kB for each one). I thought that I could use IdHTTP:

procedure TForm2.DownloadFile(filename, path: string);
var Stream: TMemoryStream;
    Url: String;
begin

  Url := filename;
  Stream := TMemoryStream.Create;

  try
    IdHTTP1.Get(Url, Stream);
    Stream.SaveToFile(path);
  finally
    Stream.Free;
    IdHTTP1.Free;
  end;

end;

This is the most common way I guess and it works pretty fine. By the way, according with what I have said above, I have to download more than a file and the solution would be:

DownloadFile('www.website.com/folder/file1.png', 'C:\folder\file1.png');
DownloadFile('www.website.com/folder/file2.png', 'C:\folder\file2.png');
DownloadFile('www.website.com/folder/file3.png', 'C:\folder\file3.png');

And so on. I also have a progressbar that indicates the progression of the downloads.

Question

Is there a more efficient way to do this? Like for instance passing to IdHTTP a list containing all the links and the file names that have to be downloaded.

Upvotes: 1

Views: 3602

Answers (1)

Mojtaba Tajik
Mojtaba Tajik

Reputation: 1733

You can use Generics like TDictionary :

function DownloadFiles(FilesInfo: TDictionary<string, string>): Boolean;
var
  FileNo: Integer;
  Stream: TFileStream;
begin
  for FileNo := Low to High do
  begin
    Stream := TFileStream.Create(FilesInfo.Values[FileNo], fmCreate);
    try
      IdHTTP1.Get(FilesInfo.Keys[FileNo], Stream);
    finally
      Stream.Free;
    end;
  end;
end;

Use :

var
  FilesInfo: TDictionary<string, string>;
begin
  FilesInfo := TDictionary<string, string>.Create();
  try
    FilesInfo.Add('www.website.com/folder/file1.png', 'C:\folder\file1.png');
    FilesInfo.Add('www.website.com/folder/file2.png', 'C:\folder\file2.png');
    FilesInfo.Add('www.website.com/folder/file3.png', 'C:\folder\file3.png');
    DownloadFiles(FilesInfo);
  finally
    FilesInfo.Free;
  end;
end;

Upvotes: 4

Related Questions