跳到主要内容

分片上传 websocket

服务端

const WebSocket = require('ws');
const fs = require('fs');

const wss = new WebSocket.Server({ port: 3000 });

wss.on('connection', (ws) => {
ws.on('message', (message) => {
const data = JSON.parse(message);

if (data.type === 'start') {
// Client sends 'start' message to initiate file upload
console.log(`File upload started: ${data.filename}`);
ws.filename = data.filename;
ws.filesize = data.filesize;
ws.filestream = fs.createWriteStream(`./uploads/${ws.filename}`);
ws.sentChunks = 0;
} else if (data.type === 'chunk') {
// Client sends file chunks
ws.filestream.write(Buffer.from(data.chunk, 'base64'));
ws.sentChunks++;

if (ws.sentChunks * 1024 * 1024 >= ws.filesize) {
// File upload complete
ws.filestream.end();
console.log(`File upload complete: ${ws.filename}`);
}
}
});
});

const WebSocket = require('ws');
const fs = require('fs');

const ws = new WebSocket('ws://localhost:3000');

const filename = 'example.txt';
const filepath = `./${filename}`;
const filesize = fs.statSync(filepath).size;

const startMessage = {
type: 'start',
filename,
filesize,
};

ws.on('open', () => {
// Send 'start' message to initiate file upload
ws.send(JSON.stringify(startMessage));

const fileStream = fs.createReadStream(filepath, { highWaterMark: 1024 * 1024 });

fileStream.on('data', (chunk) => {
// Send file chunks
const chunkMessage = {
type: 'chunk',
chunk: chunk.toString('base64'),
};

ws.send(JSON.stringify(chunkMessage));
});

fileStream.on('end', () => {
console.log('File upload complete');
});
});