Reputation: 81
I need to upload multiple files using perl cgi. i used form type as
enctype="multipart/form-data and also set multiple='multiple' in input type file.
just need to know what should we do write at server side ?
Can anybody tell me how to upload multiple files using perl?
Upvotes: 2
Views: 4139
Reputation: 61
The following piece of code is enough and upload files present in the params to /storage location:
use CGI;
my $cgi = new CGI;
my @files = $cgi->param('multi_files[]');
my @io_handles=$cgi->upload('multi_files[]');
foreach my $upload(@files){
print "Filename: $upload<br>";
my $file_temp_path = "/storage";
my $upload_file = shift @io_handles;
open (UPLOADFILE,">$file_temp_path/$upload") or print "File Open Error";
binmode UPLOADFILE;
while (<$upload_file>) {
print UPLOADFILE;
}
}
print "Files Upload done";
Upvotes: 3
Reputation: 3305
Something like this should handle multiple files upload:
my @fhs = $Cgi->upload('files');
foreach my $fh (@fhs) {
if (defined $fh) {
my $type = $Cgi->uploadInfo($fh)->{'Content-Type'};
next unless ($type eq "image/jpeg");
my $io_handle = $fh->handle;
open (OUTFILE,'>>','/var/directory/'.$fh);
while (my $bytesread = $io_handle->read(my $buffer, 1024)) {
print OUTFILE $buffer;
}
close (OUTFILE);
}
}
Ofc 'files' is the name of the file upload form.
Upvotes: 2
Reputation: 3484
On the server side, you first retrive the file file handle like this:
use CGI;
my $q = CGI->new();
my $myfh = $q->upload('field_name');
Now you have a filehandle to the temporary storage whither the file was uploaded.
The uploaded file anme can be had using the param() method.
$filename = $q->param('field_name');
and the temporary file can be directly accessed via:
$filename = $query->param('uploaded_file');
$tmpfilename = $query->tmpFileName($filename);
I highly recommend giving the CGI.pm docs a good solid read, a couple of times. While not trivial, it's all rather straightforward.
Upvotes: 1