Python文件上传示例
使用Python上传文件通常有两种方法。一种是通过使用Web服务器和**CGI环境**(也称为自动化文件上传系统)的**云存储服务**。在本教程中,我们将重点介绍使用CGI(通用网关接口)环境上传文件。
此过程涉及生成用于文件上传的HTML表单和用于管理文件保存和上传到服务器的Python脚本。使用Python上传文件的步骤如下:
-
创建用于文件上传的HTML表单
-
设置支持CGI的Web服务器。
-
通过Web浏览器访问表单并提交文件
-
Python脚本处理文件上传
创建用于文件上传的HTML表单
通过创建带有**<input type="file">**的输入字段,用户可以选择要上传的文件。**<input type="submit">**将用于创建一个提交按钮,该按钮将把数据表单发送到服务器。
示例
<!DOCTYPE html>
<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>
输出

Python脚本处理文件上传
以下是将所选文件上传到服务器的Python程序。在这里,我们为上面HTML代码中的按钮(**选择文件**和**上传**)编写了操作。
- **cgitb.enable()**将激活一个异常处理程序,该处理程序将显示错误消息。
- **cgi.FieldStorage()**提供表单数据的存储。
示例
如果未上传文件,则执行以下代码将生成错误消息;如果文件上传成功,则打印成功消息。
#importing required modules
import cgi
import os
import cgitb
# Enable CGI error reporting
cgitb.enable()
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get the file item from the form
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 the file and write its contents to the server
with open('/tmp/' + fn, 'wb') as f:
f.write(fileitem.file.read())
# Success message
message = f'The file "{fn}" was uploaded successfully'
else:
# Error message
message = 'No file was uploaded'
# Print the HTTP headers and HTML content
print(f"""\
Content-Type: text/html\n
<html>
<body>
<p>{message}</p>
</body>
</html>
""")
输出
如果文件上传成功,则服务器将响应如下:
The file "Text.txt" was uploaded successfully
如果未上传文件,则服务器将响应如下:
No file was uploaded
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP