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: <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
相关产品推荐
相关产品推荐

