【Node.js】大文件上传(分片上传)
在Node.js中实现大文件的分片上传,你可以使用以下步骤:
- 前端将文件分割成多个分片。
- 逐个上传分片到服务器。
- 服务器端接收分片并暂存,最后合并分片为原文件。
以下是实现分片上传的示例代码:
前端(HTML + JavaScript)
<form id="uploadForm">
<input type="file" id="file" name="file"/>
<button type="button" onclick="uploadFile()">Upload</button>
</form>
<script>
function uploadFile() {
const file = document.getElementById('file').files[0];
const chunkSize = 1024 * 1024; // 每个分片的大小,这里以1MB为例
const totalChunks = Math.ceil(file.size / chunkSize);
for (let i = 0; i < totalChunks; i++) {
const chunk = file.slice(chunkSize * i, i === totalChunks - 1 ? file.size : chunkSize * (i + 1));
const formData = new FormData();
formData.append('chunk', chunk);
formData.append('filename', file.name);
formData.append('chunkedIndex', i);
formData.append('totalChunks', totalChunks);
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data));
}
}
</script>
服务端(Node.js + Express)
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const port = 3000;
app.use(express.json());
app.use(express.static('public'));
app.post('/upload', (req, res) => {
const filename = req.body.filename;
const chunkedIndex = req.body.chunkedIndex;
const totalChunks = req.body.totalChunks;
const chunk = req.body.chunk;
const filePath = path.join(__dirname, 'public', filename);
const writeStream = fs.createWriteStream(filePath, { flags: 'r+' });
writeStream.on('open', () => {
writeStream.write(chunk, {
encoding: 'base64',
position: chunkedIndex * chunk.length
});
writeStream.close();
res.json({ status: 'Chunk uploaded successfully', chunkedIndex });
});
writeStream.on('error', (err) => {
console.error(err);
res.status(500).json({ error: 'Error writing to file' });
});
writeStream.on('finish', () => {
if (chunkedIndex === totalChunks - 1) {
console.log('Upload completed
评论已关闭