如何使用 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
以下脚本 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("", "/" ))
广告