简体   繁体   中英

perl file upload can't init filehandle

I tried to use this very simple script for uploading a file to my server. For some reason it is not working. I get the following message in my apache error log:


Use of uninitialized value in <HANDLE> at /opt/www/demo1/upload/image_upload_2.pl line 15.
readline() on unopened filehandle at /opt/www/demo1/upload/image_upload_2.pl line 15.

#!/usr/bin/perl -w

use CGI;  

 $upload_dir = "/opt/www/demo1/upload/data"; 
 $query = new CGI; 
 $filename = $query->param("photo"); 
 $filename =~ s/.*[\/\\](.*)/$1/; 
 $upload_filehandle = $query->upload("photo"); 

 open UPLOADFILE, ">$upload_dir/$filename"; 
 binmode UPLOADFILE; 

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

 close UPLOADFILE;

 1

Any ideas what is wrong there? Thanks mx

File upload forms need to specify enctype="multipart/form-data" . See W3C documentation .

In addition, note the following:

#!/usr/bin/perl

use strict; use warnings;
use CGI;

my $upload_dir = "/opt/www/demo1/upload/data"; 
my $query = CGI->new; # avoid indirect object notation

my $filename = $query->param("photo"); 
$filename =~ s/.*[\/\\](.*)/$1/; # this validation looks suspect

my $target = "$upload_dir/$filename";

# since you are reading binary data, use read to
# read chunks of a specific size

my $upload_filehandle = $query->upload("photo"); 
if ( defined $upload_filehandle ) {
    my $io_handle = $upload_filehandle->handle;
    # use lexical filehandles, 3-arg form of open
    # check for errors after open
    open my $uploadfile, '>', $target
        or die "Cannot open '$target': $!";
    binmode $uploadfile;

    my $buffer;        
    while (my $bytesread = $io_handle->read($buffer,1024)) {
        print $uploadfile $buffer
            or die "Error writing to '$target': $!";
    }
    close $uploadfile
        or die "Error closing '$target': $!";
}

See CGI documentation .

If you are uploading a text file then below should be set in <head> of html file:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Otherwise the $file_name = $query->param("file_name") is defined in scalar context ( print $file_name ) and undef in file context ( <$file_name> ).

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