2010-07-07 3 views
0

파일을 내 서버에 업로드하는 데이 매우 간단한 스크립트를 사용하려고했습니다. 어떤 이유로 그것은 작동하지 않습니다. 내 아파치 오류 로그에 다음과 같은 메시지가 : 거기에 어떤 문제가 있는지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

+0

필요한 사용 권한은 무엇입니까? 그것은 777을 가지고 있습니다 - 그리고 만약 내가 프린트 아웃이라면 뭔가 효과가 있습니다. 작성하고자하는 파일도 777이지만 충돌이 심하며 CGI 객체에서 핸들을 얻지 못합니다. 스크립트를 호출하는 양식에서 다음 입력 필드가 있습니다. 그것? – marcusx

+0

'form' 태그를위한'enctype'은 무엇입니까? –

답변

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

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>) .

관련 문제