Question

I'm creating a project in Delphi for upload multiple files to a webserver, but not up more the one file on same field like on simple form php. Below my Delphi code:

procedure Http_arquivos;

var
  i: integer;
  arquivos: array [0..6] of String;
  HTTP: TIdHTTP;
  POSTData: TIdMultipartFormDataStream;

begin
  arquivos[0]:= 'c:\arquivo0.bmp';
  arquivos[1]:= 'c:\arquivo1.bmp';
  arquivos[2]:= 'c:\arquivo2.html';
  arquivos[3]:= 'c:\arquivo3.html';
  arquivos[4]:= 'c:\arquivo4.wav';
  arquivos[5]:= 'c:\arquivo5.bmp';
  arquivos[6]:= 'c:\arquivo6.txt';

  HTTP := TIdHTTP.Create(nil);
  POSTData := TIdMultipartFormDataStream.Create;

  for i:= 0 to Length(arquivos) do
  begin

    if fileexists (arquivos[i]) then 
    begin
      //showmessage(arquivos[i]);
      try
        POSTData.AddFile('files[]', arquivos[i], 'multipart/form-data');
        HTTP.Post('http://localhost/ENVIO/MultUp.php', POSTData);
      finally
        POSTData.Free;
    end;
  end;
end;
end;
Was it helpful?

Solution

There are four problems with your code:

  1. Your loop counter is wrong. You need to use Length(arquivos)-1 (or Pred(Length(arquivos)), or High(arquivos)) instead.

  2. You are calling Post() inside the loop, but it needs to be outside the loop instead.

  3. You are specifying the wrong content type for each file.

  4. You are destroying the stream on each loop iteration.

Try this instead:

POSTData := TIdMultipartFormDataStream.Create;
try
  for i := Low(arquivos) to High(arquivos) do
  begin
    if FileExists(arquivos[i]) then 
    begin
      //AddFile() will choose the content type for you based on the file extension
      POSTData.AddFile('files[]', arquivos[i]);
    end;
  end;
  HTTP.Post('http://localhost/ENVIO/MultUp.php', POSTData);
finally
  POSTData.Free;
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top