如何使用Python CGI编程进行文件上传
要上传一个文件,HTML表单必须将 enctype 属性设置为”multipart/form-data”。带有文件类型的输入标签创建了一个 ” 浏览 “按钮。
示例
<html>
<body>
<form enctype = "multipart/form-data"
action = "save_file.py" method = "post">
<p>File: <input type = "file" name = "filename" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
输出
该代码的结果是以下表单 –
File: Choose file
Upload
以下是处理文件上传的Python脚本save_file.py –
#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# 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('/tmp/' + 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,)
如果你在Unix/Linux上运行上述脚本,则需要注意将文件分隔符替换为如下方式,否则在你的Windows机器上,上述 open() 语句应该能正常工作。
fn = os.path.basename(fileitem.filename.replace("", "/" ))