0

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;
  • 1
    Indent your code, and one problem should be obvious: You're calling HTTP.Post inside the loop. Add the files to the PostData in the loop, then call HTTP.Post *once* at the end. – Roddy Feb 23 '14 at 20:17
  • I see this is your first question. However, there are some problems with it: 1. It lacks an actual question. 2. Your description is a bit short. I realize that English is not your first language. But whole sentences are appreciated. 3. Do you et any error message? If not, what happens and what should have happened? If you want more material on "how to ask a good question", I recommend [this guide](http://tinyurl.com/so-hints) and [this checklist](https://msmvps.com/blogs/jon_skeet/archive/2012/11/24/stack-overflow-question-checklist.aspx). – DasKrümelmonster Feb 23 '14 at 20:21

1 Answers1

4

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;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • +1 I've deleted my answer, as you caught a couple additional errors I didn't. (And thanks for the edit on my answer as well.) – Ken White Feb 23 '14 at 20:46
  • It works now. I don't had observed this stupid error. Thank you very much friends! :D –  Feb 23 '14 at 21:22