我正在尝试设置由python脚本处理的文件上载Web表单。当我选择一个文件并单击上传时,它表示没有上传文件。 file
对象的fileitem
字段为None。该脚本在lighthttpd服务器上运行。
脚本的代码在这里:
#!/usr/bin/env python
import cgi, os
import cgitb
cgitb.enable()
form = cgi.FieldStorage()
# A nested FieldStorage instance holds the file
fileitem = form['filename']
print "----"
print "filename", fileitem.filename
print "file", fileitem.file
print "----"
message = ''
if fileitem.file:
# It's an uploaded file; count lines
linecount = 0
while 1:
line = fileitem.file.readline()
if not line: break
linecount = linecount + 1
message = linecount
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid directory traversal attacks
fn = os.path.basename(fileitem.filename)
open('/var/cache/lighttpd/uploads/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message += 'No file was uploaded'
print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
</body></html>
""" % (message,)
html文件在这里:
<html>
<head>
<title>RepRap Pinter</title>
</head>
<body>
<H1>RepRap Printer</H1>
<form action="cgi-bin/start_print.py" method="post" encrypt="multipart/form-data">
<p><input type="file" name="filename" id="file"></p>
<p><input type="submit" value="Upload"></p>
</form>
</body>
</html>
输出是:
----
filename None
file None
----
Content-Type: text/html
<html><body>
<p>No file was uploaded</p>
</body></html>
关于文件未被上传的原因的任何想法?
答案 0 :(得分:3)
你的问题似乎在这里:
<form ... encrypt="multipart/form-data">
您要查找的属性不是encrypt
,而是enctype
。由于您缺少正确的参数,因此您的编码不是multipart-formdata,因此会忽略文件上传。
答案 1 :(得分:1)
您使用了错误的属性名称:
<form action="cgi-bin/start_print.py" method="post" encrypt="multipart/form-data">
正确的属性是enctype
,而不是encrypt
:
<form action="cgi-bin/start_print.py" method="post" enctype="multipart/form-data">