nodejs接收前端分片并组合成完整文件
-
前端将文件分成多个块,并将每个块上传到服务器。
-
服务器使用Node.js创建一个HTTP服务器或Express服务器。
-
在服务器端,我们可以使用Multer或Busboy模块来处理上传的文件块。
-
在文件上传完成之后,我们可以使用fs模块的createWriteStream()方法来将文件块写入磁盘。
-
当所有文件块都上传并写入磁盘后,我们可以使用fs模块的createReadStream()方法来读取所有文件块,并使用它们来创建完整的文件。
const express = require('express');
const multer = require('multer');
const fs = require('fs');
const app = express();
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.array('file'), (req, res) => {
const files = req.files;
const fileNames = [];
// 将文件块写入磁盘
files.forEach((file, index) => {
const fileName = `uploads/${file.originalname}-${index}`;
fs.createWriteStream(fileName).write(file.buffer);
fileNames.push(fileName);
});
// 读取所有文件块并合并成完整的文件
const writeStream = fs.createWriteStream('uploads/full-file');
fileNames.forEach((fileName) => {
const readStream = fs.createReadStream(fileName);
readStream.pipe(writeStream, { end: false });
readStream.on('end', () => {
fs.unlinkSync(fileName);
});
});
writeStream.on('finish', () => {
res.send('File uploaded and merged successfully');
});
});