html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form enctype="multipart/form-data"
action="/cgi-bin/savefile.py" method="post">
<p>选中文件: <input type="file" name="filename" /></p>
<p><input type="submit" value="上传" /></p>
</form>
</body>
</html>
.py:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import cgi, os
import cgitb;
cgitb.enable()
form = cgi.FieldStorage()
# 获取文件名
fileitem = form['filename']
# 检测文件是否上传
if fileitem.filename:
# 设置文件路径
fn = os.path.basename(fileitem.filename)
open('/tmp/' + fn, 'wb').write(fileitem.file.read())
message = '文件 "' + fn + '" 上传成功'
else:
message = '文件没有上传'
print("Content-Type: text/html")
print()
print("""
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>%s</p>
</body>
</html>
""" % message)
报错内容:
[Fri Dec 01 09:56:00.379075 2017] [http:error] [pid 11644:tid 1192] [client ::1:49200] AH02429: Response header name '<!--' contains invalid characters, aborting request, referer: http://localhost/submit_file.html
[Fri Dec 01 09:56:38.928831 2017] [http:error] [pid 11644:tid 1200] [client ::1:49256] AH02429: Response header name '<!--' contains invalid characters, aborting request, referer: http://localhost/submit_file.html
[Fri Dec 01 09:57:36.233811 2017] [http:error] [pid 11644:tid 1192] [client ::1:49343] AH02429: Response header name '<!--' contains invalid characters, aborting request, referer: http://localhost/submit_file.html
[Fri Dec 01 09:57:46.941349 2017] [http:error] [pid 11644:tid 1192] [client ::1:49349] AH02429: Response header name '<!--' contains invalid characters, aborting request, referer: http://localhost/submit_file.html
[Fri Dec 01 10:07:48.185970 2017] [http:error] [pid 11644:tid 1200] [client ::1:50250] AH02429: Response header name '<!--' contains invalid characters, aborting request, referer: http://localhost/submit_file.html
[Fri Dec 01 10:09:08.977719 2017] [http:error] [pid 11644:tid 1192] [client ::1:50355] AH02429: Response header name '<!--' contains invalid characters, aborting request, referer: http://localhost/submit_file.html
[Fri Dec 01 10:19:04.956740 2017] [http:error] [pid 11644:tid 1200] [client ::1:51325] AH02429: Response header name '<!--' contains invalid characters, aborting request, referer: http://localhost/submit_file.html
解决方法:
进过这种排查发现是这个/tmp/目录不存在导致,所以代码应该先进行os.path.isfile(path)判断,如果不存在需要先进行创建os.mkdir("file")