简体   繁体   中英

How to upload multiple files in perl?

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?

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.

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.

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM