python创建一个httpServer网页上传文件到httpServer

一、代码

1.server.py
bash 复制代码
import os 
from http.server import SimpleHTTPRequestHandler, HTTPServer 
import cgi 
 
# 自定义请求处理类
class MyRequestHandler(SimpleHTTPRequestHandler):
    # 处理GET请求
    def do_GET(self):
        if self.path == '/':
            # 响应200状态码
            self.send_response(200)
            # 设置响应头为text/html
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            # 读取并发送upload.html文件内容
            with open('upload.html', 'rb') as file:
                self.wfile.write(file.read())
        else:
            # 调用父类方法处理其他路径的GET请求
            super().do_GET()
 
    # 处理POST请求
    def do_POST(self):
        if self.path == '/upload':
            # 解析表单数据
            form = cgi.FieldStorage(
                fp=self.rfile,
                headers=self.headers,
                environ={'REQUEST_METHOD': 'POST',
                         'CONTENT_TYPE': self.headers['Content-Type']}
            )
            if 'file' in form:
                file_item = form['file']
                if file_item.filename:
                    # 构建文件保存路径
                    file_path = os.path.join('uploads', file_item.filename)
                    # 将上传的文件保存到指定路径
                    with open(file_path, 'wb') as f:
                        f.write(file_item.file.read())
                    # 响应200状态码
                    self.send_response(200)
                    # 设置响应头为text/html
                    self.send_header('Content-type', 'text/html')
                    self.end_headers()
                    # 发送上传成功的消息
                    self.wfile.write('文件上传成功'.encode('utf-8'))
                else:
                    # 如果没有选择文件,返回400错误
                    self.send_error(400, '未选择文件')
            else:
                # 如果缺少文件字段,返回400错误
                self.send_error(400, '缺少文件字段')
        else:
            # 如果路径不存在,返回404错误
            self.send_error(404, '未找到')
 
# 主程序入口
if __name__ == '__main__':
    # 检查并创建上传目录
    if not os.path.exists('uploads'):
        os.makedirs('uploads')
 
    # 定义服务器端口号
    PORT = 8000 
    # 创建HTTP服务器
    with HTTPServer(('', PORT), MyRequestHandler) as httpd:
        print(f'服务器运行在端口 {PORT}')
        # 启动服务器,持续监听请求
        httpd.serve_forever()
2.upload.html
html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传</title>
</head>
<body>
    <h1>上传文件</h1>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <label for="file">选择要上传的文件:</label>
        <input type="file" id="file" name="file" required>
        <br><br>
        <button type="submit">上传</button>
    </form>
</body>
</html>
3.upload.html 可显示进度条
html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传</title>
    <style>
        #progressBarContainer {
            width: 100%;
            background-color: #f3f3f3;
            margin-top: 10px;
        }
        #progressBar {
            width: 0%;
            height: 20px;
            background-color: #4caf50;
            text-align: center;
            line-height: 20px;
            color: white;
        }
    </style>
</head>
<body>
    <h1>上传文件</h1>
    <form id="uploadForm" enctype="multipart/form-data">
        <label for="file">选择要上传的文件:</label>
        <input type="file" id="file" name="file" required>
        <br><br>
        <div id="progressBarContainer">
            <div id="progressBar">0%</div>
        </div>
        <button type="button" onclick="uploadFile()">上传</button>
    </form>

    <script>
        function uploadFile() {
            var form = document.getElementById('uploadForm');
            var formData = new FormData(form);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/upload', true);

            // 更新进度条
            xhr.upload.onprogress = function(event) {
                if (event.lengthComputable) {
                    var percentComplete = (event.loaded / event.total) * 100;
                    var progressBar = document.getElementById('progressBar');
                    var progressText = document.createTextNode(Math.round(percentComplete) + '%');
                    progressBar.style.width = percentComplete + '%';
                    progressBar.innerHTML = ''; // 清空旧文本
                    progressBar.appendChild(progressText); // 添加新文本
                }
            };

            xhr.onload = function() {
                if (xhr.status === 200) {
                    alert('文件上传成功!');
                } else {
                    alert('文件上传失败!');
                }
            };

            xhr.onerror = function() {
                alert('上传过程中发生错误!');
            };

            xhr.send(formData);
        }
    </script>
</body>
</html>
4. serverOpen.bat
bash 复制代码
@echo off  
REM 关闭命令回显,使输出更干净 
python server.py
REM 启动命令提示符 
start cmd 

二、测试

双击serverOpen.bat运行httpServer

uploads文件夹下出现

相关推荐
mahuifa1 小时前
(7)python开发经验
python·qt·pyside6·开发经验
学地理的小胖砸3 小时前
【Python 操作 MySQL 数据库】
数据库·python·mysql
安迪小宝3 小时前
6 任务路由与负载均衡
运维·python·celery
Blossom.1183 小时前
使用Python实现简单的人工智能聊天机器人
开发语言·人工智能·python·低代码·数据挖掘·机器人·云计算
da-peng-song3 小时前
ArcGIS Desktop使用入门(二)常用工具条——数据框工具(旋转视图)
开发语言·javascript·arcgis
galaxy_strive3 小时前
qtc++ qdebug日志生成
开发语言·c++·qt
TNTLWT3 小时前
Qt功能区:简介与安装
开发语言·qt
lisw053 小时前
Python高级进阶:Vim与Vi使用指南
python·vim·excel
ayiya_Oese3 小时前
[模型部署] 3. 性能优化
人工智能·python·深度学习·神经网络·机器学习·性能优化
SoraLuna3 小时前
「Mac畅玩AIGC与多模态40」开发篇35 - 用 Python 开发服务对接 SearxNG 与本地知识库
python·macos·aigc