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文件夹下出现

相关推荐
m0_736919103 小时前
C++代码风格检查工具
开发语言·c++·算法
喵手3 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934733 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy3 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
黎雁·泠崖4 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472464 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
肖永威5 小时前
macOS环境安装/卸载python实践笔记
笔记·python·macos
TechWJ5 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
枷锁—sha5 小时前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全
abluckyboy5 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法