perl文件上傳程序,支持多文件,2進制

- 中國WEB開發者網絡 (http://www.webasp.net)
-- 技術教程 (http://www.webasp.net/article/)
--- perl文件上傳程序,支持多文件,2進制 (http://www.webasp.net/article/8/7747.htm)
-- 作者:未知
-- 發佈日期: 2003-09-13
一個真正支持二進制文件上傳,允許多文件上傳,可以對文件後綴進行限制,生成完整信息的小程序。。:)

其實是我看了精華區的那篇文件上傳文件後,感覺有點問題,所以特此更正一下,在此也感謝以前無私奉獻的各位兄弟。。
原先的上傳由於沒有採用binmode方法,所以如果上傳圖片或二進制文件都會出錯,現在這個都已經解決了,而且還可以多文件同時上傳。。:)另外加了註釋。
最後,我是一個PERL新手,如有不當,還望各位高手指點一二,小生不勝感激:)

代碼如下:
default.htm:
<html>
<body>
<form method="POST" action="psupload.pl" ENCTYPE="multipart/form-data">
File 1:
<input type="file" name="FILE1">
<br>
File 2:
<input type="file" name="FILE2">
<br>
<input type="submit" value="Upload!">
</form>
</body>
</html>

psupload.pl:
#如果用CGI方式來行動這個文件,請把下段路徑改成你的機器配置
#!f:/activeperl/bin/perl

use CGI;
$upfilecount = 1;
$maxuploadcount = 2; #限制上傳文件的最大數
$basedir = "c:/perltest/perlupload"; #上傳的文件存放地址
$allowall = "no"; #是否不限制文件後綴上傳
@theext =(".zip",".exe",".gif"); #要限制的文件後綴名

print "Content-type: text/html\n\n";

while ($upfilecount <= $maxuploadcount) {
    my $req = new CGI;
    my $file = $req->param("FILE$upfilecount");
    if ($file ne "") {
        my $fileName = $file;
        $fileName =~ s/^.*(\\|\/)//; #用正則表達式去除無用的路徑名,得到文件名
        my $newmain = $fileName;
        my $filenotgood;
        if ($allowall ne "yes") {
            $extname = lc(substr($newmain,length($newmain) - 4,4)); #取後綴名
            for(my $i = 0; $i < @theext; $i++){ #這段進行後綴名檢測
                if ($extname eq $theext[$i]){
                    $filenotgood = "yes";
                    last;
                }
            }
        }
        if ($filenotgood ne "yes") { #這段開始上傳
            open (OUTFILE, ">$basedir/$fileName");
            binmode(OUTFILE); #務必全用二進制方式,這樣就可以放心上傳二進制文件了。而且文本文件也不會受干擾
            while (my $bytesread = read($file, my $buffer, 1024)) {
                print OUTFILE $buffer;
            }
            close (OUTFILE);
            $message.=$file . " 已成功上傳!<br>\n";
        }
        else{
            $message.=$file . " 文件後綴不符合要求,上傳失敗!<br>\n";
        }
    }
    $upfilecount++;
}

print $message; #最後輸出上傳信息 

webasp.net