python创建一个httpServer网页上传文件到httpServer
一、代码
1.server.py
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
<!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 可显示进度条
<!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
@echo off
REM 关闭命令回显,使输出更干净
python server.py
REM 启动命令提示符
start cmd
二、测试
双击serverOpen.bat运行httpServer
uploads文件夹下出现
原文地址:https://blog.csdn.net/lljss1980/article/details/145279786
免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!