网页文件上传总是损坏

Web page file upload is always corrupted

我正在尝试将文件上传添加到现有网页。

每次上传时,我都会收到一个损坏的文件。

我确保在文件句柄上设置 binmode。我还在我的表单中将我的输入 enctype 设置为 multipart/formdata

我的代码如下

$article{upload_file_name} = $cgi->param( 'upFile' );
$article{upload_file}      = $cgi->upload( 'upFile' );

if ( $article{upload_file_name} ne "" or $article{upload_file_name} ne null ) {

    open( UPLOADS, ">$uploads_dir/$article{upload_file_name}" )
            or die "Could not open $uploads_dir/$article{upload_file_name}";

    binmode UPLOADS;

    while ( <$article{upload_file}> ) {
        print UPLOADS;
    }

    close UPLOADS;
}

我也试过这个

$article{upload_file} = $cgi->param( 'upFile' );

if ( $article{upload_file} ne "" or $article{upload_file} ne null ) {

    open( UPLOADS, ">$uploads_dir/$article{upload_file}" )
            or die "Could not open $uploads_dir/$article{upload_file}";
    binmode UPLOADS;

    while ( <$article{upload_file}> ) {
        print UPLOADS;
    }

    close UPLOADS;
}
<$article{upload_file}>

并没有按照您认为的那样去做。菱形运算符 (<>) 用于代表 Perl 的 readline function, but it has a second meaning where it does the same thing as Perl's glob 函数。而在 Perl 的解析规则中,<$hash{key}> 总是被视为 glob.

perldoc -f perlop 说明:

If what's within the angle brackets is neither a filehandle nor a simple scalar variable containing a filehandle name, typeglob, or typeglob reference, it is interpreted as a filename pattern to be globbed, and either a list of filenames or the next filename in the list is returned, depending on context. This distinction is determined on syntactic grounds alone. That means <$x> is always a readline() from an indirect handle, but <$hash{key}> is always a glob(). That's because $x is a simple scalar variable, but $hash{key} is not--it's a hash element. Even <$x > (note the extra space) is treated as glob("$x "), not readline($x).

至少有几个解决方法:

  1. 使用显式 readline 调用:

    while (readline($article{upload_file}))
    
  2. 将文件句柄分配给简单标量

    my $upload_fh = $article{upload_file};
    ...
    while (<$upload_fh>)