在Python中使用HTTPServer()实现文件上传和下载功能
发布时间:2024-01-02 05:54:11
在Python中,可以使用HTTPServer模块实现文件上传和下载功能。HTTPServer是Python标准库中的一个模块,它提供了一个简单的HTTP服务器,可以用于处理http请求。
要实现文件上传和下载功能,我们需要使用HTTPServer模块的BaseHTTPRequestHandler类,并重写其中的do_GET和do_POST方法。
下面是一个文件上传和下载功能的示例代码:
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
class FileServerHandler(BaseHTTPRequestHandler):
def do_GET(self):
# 处理GET请求,即文件下载功能
file_path = '.' + self.path
if os.path.exists(file_path) and os.path.isfile(file_path):
# 如果文件存在,则发送文件内容
self.send_response(200)
self.send_header('Content-Type', 'application/octet-stream')
self.send_header('Content-Disposition', 'attachment; filename=' + os.path.basename(file_path))
self.end_headers()
with open(file_path, 'rb') as f:
self.wfile.write(f.read())
else:
# 如果文件不存在,则返回404错误
self.send_response(404)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(b'File not found')
def do_POST(self):
# 处理POST请求,即文件上传功能
content_length = int(self.headers['Content-Length'])
data = self.rfile.read(content_length)
file_name = os.path.basename(self.path)
with open(file_name, 'wb') as f:
f.write(data)
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(b'File uploaded successfully')
def run(server_class=HTTPServer, handler_class=FileServerHandler, port=8000):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
if __name__ == '__main__':
run()
在以上代码中,我们首先定义了一个自定义类FileServerHandler继承自BaseHTTPRequestHandler,并重写了其中的do_GET和do_POST方法。
在do_GET方法中,我们处理GET请求,即文件下载功能。首先通过self.path获取请求的文件路径,然后判断文件是否存在,存在则发送文件内容,不存在则返回404错误。
在do_POST方法中,我们处理POST请求,即文件上传功能。首先通过self.headers['Content-Length']获取请求的数据长度,然后通过self.rfile.read方法读取数据内容,将其写入文件中。
最后在main函数中,我们调用run函数启动HTTP服务器,默认监听8000端口。
假设我们将以上代码保存为server.py,并运行该文件。然后使用浏览器访问http://localhost:8000/upload,将文件上传到服务器。然后再访问http://localhost:8000/download,即可下载刚刚上传的文件。
这就是使用HTTPServer模块实现文件上传和下载功能的简单示例。根据实际需求,可以对代码进行扩展,添加更多的功能。
