利用BaseHTTPRequestHandler实现文件上传功能的示例
发布时间:2023-12-24 07:23:16
下面是一个使用Python标准库中的BaseHTTPRequestHandler实现文件上传功能的示例:
from http.server import BaseHTTPRequestHandler
import os
class FileUploadHandler(BaseHTTPRequestHandler):
def do_POST(self):
# 设置上传文件保存的目录
upload_dir = "upload"
if not os.path.exists(upload_dir):
os.makedirs(upload_dir)
# 获取上传的文件名
content_type = self.headers['Content-Type']
if 'multipart/form-data' in content_type:
_, params = content_type.split(';')
boundary = params.split('=')[1].strip()
line = self.rfile.readline()
while line and boundary.encode() not in line:
line = self.rfile.readline()
if line:
filename = line.decode().strip().split(';')[2].split('=')[1].strip().strip('"')
filepath = os.path.join(upload_dir, filename)
# 保存上传的文件
with open(filepath, 'wb') as f:
line = self.rfile.readline()
while line and boundary.encode() not in line:
f.write(line)
line = self.rfile.readline()
# 返回上传成功的信息
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'Successfully uploaded!')
return
# 返回上传失败的信息
self.send_response(500)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'Failed to upload file!')
if __name__ == '__main__':
from http.server import HTTPServer
server = HTTPServer(('localhost', 8000), FileUploadHandler)
print('Starting server at http://localhost:8000')
server.serve_forever()
上述代码创建了一个继承自BaseHTTPRequestHandler的自定义类FileUploadHandler,该类覆盖了do_POST()方法,用于处理POST请求。
具体实现的步骤如下:
- 设置保存上传文件的目录为"upload",如果目录不存在则创建。
- 解析请求头中的Content-Type,判断是否为multipart/form-data类型。如果是,则通过boundary分割请求内容,获取上传的文件名。
- 读取请求内容,直到遇到boundary结束符号,将内容写入上传文件。
- 返回上传成功或失败的信息回客户端。
使用该文件上传功能的例子可以通过curl命令来测试。假设服务器运行在localhost的8000端口,以下是上传文件的示例命令:
curl -X POST -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryABCDEFG" --data-binary @path/to/file http://localhost:8000
其中,------WebKitFormBoundaryABCDEFG是boundary值,path/to/file是待上传的文件的路径。执行这个命令,文件将被上传到服务器的"upload"目录下。如果文件上传成功,服务器会返回"Successfully uploaded!",否则返回"Failed to upload file!"。
注意,这只是一个简单的示例,可能无法处理一些边界情况,如文件名带有非法字符或文件大小超过限制等。在实际应用中,建议使用成熟的Web框架,如Django或Flask,来处理文件上传功能。
