Search code examples
htmlperlcgi

Upload file using Perl CGI


I am able to create my directory but I cannot seem to place the file in the directory.

#!/usr/bin/perl

use Cwd;
use CGI;

my $dir = getcwd();
print "Current Working Directory: $ dir\n";

my $photoDir = "$dir/MyPhotos";

mkdir $photoDir
        or die "Cannot mkdir $photoDir: $!"
        unless -d $photoDir;
        
        
my $query = new CGI;
my $filename = $query->param("Photo");
my $description = $query->param("description");

print "Current filename: $filename\n";

my ( $name, $path, $extension ) = fileparse ( $filename, '\..*' ); $filename = $name . $extension;
print $filename;
my $upload_filehandle = $query->upload("Photo");



open ( UPLOADFILE, ">$photoDir/$filename" )
 or die "$!"; 
binmode UPLOADFILE; 

while ( <$upload_filehandle> ) 
{ print UPLOADFILE; } 
close UPLOADFILE;

The CGI stack trace shows no errors but the log shows there is no output

LOG: 5 5020-0:0:0:0:0:0:0:1%0-9: CGI output 0 bytes.

Solution

  • Update: This answer is outdated, today you will get an IO::File compatible handle directly:

    # undef may be returned if it's not a valid file handle
    if ( my $io_handle = $q->upload('field_name') ) {
        open ( my $out_file,'>>','/usr/local/web/users/feedback' );
        while ( my $bytesread = $io_handle->read($buffer,1024) ) {
            print $out_file $buffer;
        }
    }
    

    Please see the updated documentation.


    Original answer:

    CGI.pm manual suggests this path to saving uploaded files. Try this additional check and write method and see if it helps.

         $lightweight_fh  = $q->upload('field_name');
    
         # undef may be returned if it's not a valid file handle
         if (defined $lightweight_fh) {
           # Upgrade the handle to one compatible with IO::Handle:
           my $io_handle = $lightweight_fh->handle;
    
           open (OUTFILE,'>>','/usr/local/web/users/feedback');
           while ($bytesread = $io_handle->read($buffer,1024)) {
             print OUTFILE $buffer;
           }
         }
    

    Also make sure you have your HTML form has required type like this: <form action=... method=post enctype="multipart/form-data">