perl文件上传不能初始化文件句柄

时间:2010-07-07 16:22:49

标签: perl

我尝试使用这个非常简单的脚本将文件上传到我的服务器。由于某种原因,它无法正常工作。我在apache错误日志中收到以下消息:


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

有什么想法吗? 谢谢 MX

2 个答案:

答案 0 :(得分:6)

文件上传表单需要指定enctype="multipart/form-data"。请参阅W3C documentation

此外,请注意以下事项:

#!/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': $!";
}

请参阅CGI documentation

答案 1 :(得分:0)

如果您要上传文本文件,则应在html文件的<head>中设置以下内容:

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

否则$file_name = $query->param("file_name")在标量上下文(print $file_name)和文件上下文中的undef(<$file_name>)中定义。