最近在学习websocket的使用,配合web前端来实现一些功能
通过下述代码可以接收来自前端的path信息,并将所需的文件传输至web前端
import asyncio
import websockets
import os
from urllib import parse
async def send_file(websocket, path):
file_size = os.path.getsize(path)
file_name = os.path.basename(path)
chunk_size = 1024 # 每次发送的字节数
# 发送文件大小给客户端,以便客户端知道要接收多少数据
await websocket.send(str(file_size) + "&" + file_name)
with open(path, 'rb') as f:
while True:
data = f.read(chunk_size)
if not data:
break
await websocket.send(data)
async def handler(websocket, path):
path = parse.unquote(path)
getData = path.split('/')
if getData[1] == 'file':
# 假设你要发送的文件是固定的,或者通过某种方式得知要发送哪个文件
file_path = f'files/{getData[2]}'
# 检查文件是否存在
if os.path.exists(file_path):
await send_file(websocket, file_path)
else:
await websocket.send("File not found")
async def main():
async with websockets.serve(handler, "localhost", 8765):
print("websocket启动")
await asyncio.Future()
if __name__ == '__main__':
asyncio.run(main())
下述js代码可以接收来自python服务端的文件并将其进行下载:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket 文件接收</title>
</head>
<body>
<h1>WebSocket 文件接收</h1>
<button onclick="connectToServer()">连接到服务器</button>
<div id="status"></div>
<script >
// client.js
let socket;
let fileSize;
let fileName;
let receivedBytes = 0;
let fileBlob = new Blob();
function connectToServer() {
// 连接到WebSocket服务器
socket = new WebSocket('ws://localhost:8765/file/甲.xlsx');
socket.onopen = function(event) {
console.log('已连接到服务器');
document.getElementById('status').innerText = '已连接到服务器';
};
socket.onmessage = function(event) {
const message = event.data;
// 检查是否是文件大小和名称信息
if (typeof message === 'string') {
let fileData=message.split("&");
fileSize = parseInt(fileData[0]);
fileName=fileData[1];
return;
}
const chunkBlob = new Blob([message], { type: 'application/octet-stream' });
fileBlob = new Blob([fileBlob, chunkBlob], { type: 'application/octet-stream' });
receivedBytes += message.size;
console.log(`已接收 ${receivedBytes} 字节`);
if (receivedBytes >= fileSize) {
console.log('文件接收完成');
downloadFile(fileBlob);
socket.close();
}
};
socket.onerror = function(error) {
console.error('WebSocket 错误:', error);
};
socket.onclose = function(event) {
console.log('WebSocket 连接已关闭');
};
}
function downloadFile(blob) {
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName; // 设置下载文件的名称
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
</script>
</body>
</html>
至此可以完成文件的传输和下载