2010-07-07 91 views
0

我試圖用這個非常簡單的腳本上傳文件到我的服務器。由於某種原因,它不起作用。我在Apache的錯誤日誌中得到以下信息:perl文件上傳不能初始化文件句柄


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

+0

該文件是否真的存在?您的腳本是否具有訪問它的正確權限? – mcandre 2010-07-07 16:28:39

+0

什麼權限是neccesary?它有777 - 如果我打印出它正在工作的東西。我想要編寫的文件也是777,但它崩潰了,它不會從CGI對象獲取句柄。 在調用腳本的窗體中,我有以下輸入字段: 這是正確的,不是它? – marcusx 2010-07-07 16:36:23

+0

「form」標記的'enctype'是什麼? – 2010-07-07 16:40:55

回答

5

文件上傳表格需要指定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

+0

文件上傳表單需要指定enctype =「multipart/form-data」。 這就是訣竅!謝謝!! (還有其他提示) – marcusx 2010-07-09 14:29:42

0

如果您上傳文本文件,然後下面應該在HTML文件的<head>設置:

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

否則$file_name = $query->param("file_name")在標量上下文(print $file_name)和聯合國民主基金在文件上下文定義(<$file_name>) 。