以下为runoob.com中提供的程序:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form enctype="multipart/form-data"
action="/cgi-bin/save_file.py" method="post">
<p>选中文件: <input type="file" name="filename" /></p>
<p><input type="submit" value="上传" /></p>
</form>
</body>
</html>
#!/usr/bin/python3
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\n
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>%s</p>
</body>
</html>
""" % (message,))
经过检查,error.log错误提示,
及论坛释疑,应是/tmp/目录不存在导致,
更改此处地址,程序运行成功。
#!D:\Python310\python.exe
#-*- coding: utf8 -*-
import cgi, os
import cgitb; cgitb.enable()
import codecs, sys
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())#不加会乱码
form = cgi.FieldStorage()
# 获取文件名
fileitem = form['filename']
# 检测文件是否上传
if fileitem.filename:
# 设置文件路径
fn = os.path.basename(fileitem.filename)
open('D:/Apache24/cgi-bin/tmp/' + fn, 'wb').write(fileitem.file.read())
message = '文件 "' + fn + '" 上传成功'
else:
message = '文件没有上传'
print ("""\
Content-Type: text/html\n
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>%s</p>
</body>
</html>
""" % (message,))
注意,tmp后面的/不能漏,否则上传的文件名会被修改为tpm+"文件名“。
不要直接从资源管理器上直接复制地址,如:
D:\Apache24\cgi-bin\tmp
此处为" \ ",程序会报错,需改为" / "。经查,这二者的区别为前者为本地地址,后者为外部地址,因是调用apache上执行此程序,可能程序认为这个地址是一个外部地址吧。