2011-02-22 52 views
1

基於this article,我編寫了一個perl腳本以允許將文檔文件上傳到我的網站。但是我得到「不能在upload.cgi第38行使用未定義的值作爲HASH參考。」 (第38行是except從句之上的那一行)。 作爲參考,我的虛擬主機安裝了Perl 5.8.8。Perl「未定義值作爲HASH參考」錯誤

#!/usr/bin/perl -wT 

use strict; 
use CGI qw/param uploadInfo/; 
use CGI::Carp qw (fatalsToBrowser); 
use File::Basename; 

$CGI::POST_MAX = 1024 *1024 * 50; #Max file size 50MB 
my $safe_filename_characters = "a-zA-Z0-9_.-"; 
my $upload_dir = "/home/antrobus/Originals"; 

my $query = new CGI; 
my $filename = $query->param("manuscript"); 

if (!$filename) 
{ 
print $query->header (); 
print "The file is too large. Please email me to arrange other means of providing your manuscript."; 
exit; 
} 

my ($name, $path, $extension) = fileparse ($filename, '\..*'); 
$filename = $name . $extension; 
$filename =~ tr/ /_/; 
$filename =~ s/[^$safe_filename_characters]//g; 

if ($filename =~ /^([$safe_filename_characters]+)$/) 
{ 
$filename = $1; 
} 
else 
{ 
die "Filename contains invalid characters"; 
} 

my @allowedtypes = qw(application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document application/vnd.oasis.opendocument.text application/rtf); 
my $type = uploadInfo($filename)->{'Content-Type'}; 
unless ($type = @allowedtypes) 
{ 
print $query->header (); 
print "Filetype not allowed. Please upload doc, docx, odt, or rtf files only."; 
exit; 
} 

my $upload_filehandle = $query->upload("manuscript"); 

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

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

close UPLOADFILE; 

print $query->header (); 
print qq~; 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>File Uploaded!</title> 
    <style type="text/css"> 
    img {border: none;} 
    </style> 
</head> 
<body> 
    <p>Thanks for uploading your manuscript!</p> 
</body> 
</html> 
~; 
+0

'$ type = @ allowedtypes'表達式看起來很腥。除非($ type ~~ @ allowedtypes)',否則會期望類似'unless($ allowedtypes {$ type})'或(with 5.10)''。 –

+0

改爲'unless($ allowedtypes {$ type})'會產生以下錯誤:「全局符號」%allowedtypes「需要在upload.cgi第38行顯式包名。」 –

回答

1

找到了答案here。顯然,檢查混亂的方法會干擾檢查MIME內容類型的能力。將$filename複製到另一個變量之前,檢查並使用其他變量works ...接受它接受任何文件類型,而不僅僅是接受的四個(但這是另一個問題!)

2

如果你想從CGI有MIME內容類型

不喜歡它,

$type = $query->uploadInfo($filename)->{'Content-Type'};CGI對象失蹤

看到CGI更多細節, ,特別是

$filename = $q->param('uploaded_file'); 
$type = $q->uploadInfo($filename)->{'Content-Type'}; 
unless ($type eq 'text/html') { 
     die "HTML FILES ONLY!"; 
} 
+0

添加'$ q->'或'$ query->「沒有任何作用,我寫了我的代碼片段基於該CGI文檔我刪除了$查詢對象,因爲它最初產生一個未定義的子例程錯誤 –