如何使用 Python CGI 编程执行文件上传?


要上传文件,HTML 表单必须有一个将 enctype 属性设置为 multipart/form-data。具有文件类型的 input 标记创建一个“浏览”按钮。

示例

<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

以下是处理文件上传的 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("", "/" ))

更新于:09-9-2023

3K+ 浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告