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

Hi, I have a form that uploads multiple files using input type "file". I found this piece of code that saved the file on the server, my question is, how do I change it so it supports multiple files?
my $my_cgi new CGI; my $upload_filehandle = cgi ->upload('file1'); my $filename = $cgi->param('file1'); $filename =~ s/.*[\/\\](.*)/$1/; if ($upload_filehandle) { open(FILE1, ">$upload_dir/$filename") || print("Could not open fil +e!"); binmode FILE1; while (<$upload_filehandle>) { print FILE1 ; } close FILE1; }
Thanks!

Replies are listed 'Best First'.
Re: How to save multiple uploaded files on the server?
by Anonymous Monk on Sep 14, 2015 at 00:18 UTC

      So maybe something along these lines

      use CGI 4.20; use File::Copy qw/ copy /; for my $key ( $cgi->all_parameters ){ for my $fh( $cgi->upload( $key ) ){ if(!$fh && $cgi->cgi_error ){ print "<p> $fh got problem", $cgi->cgi_error, "\n"; next; } else { binmode $fh; my $destFilename = "$destination/".WashFilename( "$fh" ); copy( $fh, $destFilename ) or die "Copy to ( $destFilename ) failed: (( $! ))(( $ +^E ))"; } } } ... sub WashFilename { use File::Basename; my $basename = basename( shift ); # untainted , only use a-z A-Z 0-9 and dot $basename = join '', $basename =~ m/([.a-zA-Z0-9])/g; # basename is now, hopefully, file.ext ## so to ensure uniqueness, we adulterate it :) my $id = $$.'-'.time; my( $file, $ext ) = split /\./, $basename, 2 ; return join '.', grep defined, $file, $id, $ext; } ## end sub WashFilename
        Works like a charm! Thanks :)
      Hi, I so use loop, here is the code:
      @filenames = param('files[]'); for ($filecount = 0; $filecount < @filenames; $filecount++) { $upload_filehandle = upload('files[]'); open ( UPLOADFILE, ">$upload_dir/$filenames[$filecount]" ) or die +"$!"; binmode UPLOADFILE; while ( <$upload_filehandle> ) { print UPLOADFILE; } close UPLOADFILE; }
      The result is that if for example I chose 3 files, the all 3 files are created with the correct names but only one file has the correct content, the other 2 are always size 0. What am I missing?
A reply falls below the community's threshold of quality. You may see it by logging in.