roadrunner has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I have a variable length array of files built up in my program that I wish to do an HTTP Post with using LWP with HTTP::Request::Common

Currently I am able to get this to work fine by doing:

my @files = ("C:/foo.jpg", "C:/bar.jpg"); my $ua = LWP::UserAgent->new(); my $req = POST $url, Content_Type => 'form-data', Content => [ submit => 1, file1 => [ $files[0] ], file2 => [ $files[1] ], ];

However my array could have any number of files in it, and what I'd like to do is iterate through them all and dynamically add them to the to the HTTP Post content - Does anyone know how I can do this ?

Thanks,
Roadrunner.

  • Comment on How to do an HTTP post for multiple files using HTTP::Request::Common ?
  • Download Code

Replies are listed 'Best First'.
Re: How to do an HTTP post for multiple files using HTTP::Request::Common ?
by Corion (Patriarch) on Nov 23, 2007 at 20:11 UTC

    Construct the pairs filen => $files[n-1] in a loop and pass these pairs in the constructor:

    my @fileargs = map { "file$_" => [ $files[$_-1]] } 1..scalar @files; my $ua = LWP::UserAgent->new(); my $req = POST $url, Content_Type => 'form-data', Content => [ submit => 1, @fileargs, ];
Re: How to do an HTTP post for multiple files using HTTP::Request::Common ?
by ikegami (Patriarch) on Nov 23, 2007 at 20:12 UTC
    my @files = ("C:/foo.jpg", "C:/bar.jpg"); my $ua = LWP::UserAgent->new(); my $req = POST $url, Content_Type => 'form-data', Content => [ submit => 1, (map { "file".($_+1) => [ $files[$_] ] } 0..$#files), ];
      Thanks - this worked a treat.