You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Perl CGI无法获取浏览器上传文件的文件句柄问题求助

文件上传功能排查与修复

核心问题定位

你的HTML表单存在致命错误:<form>标签的请求方法属性写错了,使用了type=POST,正确属性应为method="POST"。表单默认使用GET方法提交,而GET无法传输文件内容,这就是服务器仅能获取文件名、拿不到文件句柄的根本原因。

修复步骤

1. 修正HTML表单代码

将表单的type=POST替换为method="POST",同时规范属性引号写法:

<html>
<head>
</head>
<body>
    <h1>Find file to upload</h1>
    <p>
        <form method="POST" name="upload" id="upload" action="/cgi-bin/load_file.cgi" enctype="multipart/form-data">
            Enter path to file to upload:&nbsp;&nbsp;
            <input type="file" name="spreadsheet" id="spreadsheet">
            <button>Submit</button>
        </form>
    </p>
</body>
</html>

2. 服务器端代码补充验证建议

  • 检查CGI模块版本:确保使用较新版本的CGI.pm,旧版本可能存在上传处理兼容问题
  • 确认临时目录权限:CGI上传文件时会先将文件存入系统临时目录(默认/tmp),需保证Web服务器进程对该目录有读写权限
  • 增加错误判断逻辑,便于排查问题:
if (!$fhdl) {
    print "Upload failed: " . $cgi->error() . "<p>";
}

验证效果

修正表单后,再次上传文件,服务器端的$fhdl应返回有效文件句柄,可通过以下代码读取并保存文件内容:

if ($fhdl) {
    open my $out_fh, '>', "/path/to/save/$file" or die "Can't open output file: $!";
    while (my $line = <$fhdl>) {
        print $out_fh $line;
    }
    close $out_fh;
}

内容的提问来源于stack exchange,提问作者Doug Poulin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 13:40:16