python http文件上传

server端代码

import os
import cgi
from http.server import SimpleHTTPRequestHandler, HTTPServer

# 服务器地址和端口
host = '0.0.0.0'
port = 8080

# 处理文件上传的请求
class FileUploadHandler(SimpleHTTPRequestHandler):
    def do_POST(self):
        # 解析多部分表单数据
        form = cgi.FieldStorage(
            self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD': 'POST'}
        )

        if 'file' in form:
            file_item = form['file']
            if file_item.file:
                # 获取文件名
                file_name = os.path.basename(file_item.filename)

                # 保存上传的文件
                with open(file_name, 'wb') as f:
                    f.write(file_item.file.read())

                # 响应客户端
                self.send_response(200)
                self.end_headers()
                self.wfile.write(b'File uploaded successfully!')
        

你可能感兴趣的:(python,python,http,开发语言)