面是一种基于前端分片上传,后端合并的方法的代码实现:
前端代码(HTML + JavaScript):
html
<input type="file" id="fileInput">
<button onclick="uploadFile()">Upload</button>
<script>
function uploadFile() {
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
var chunkSize = 5 * 1024 * 1024; //每个分片大小为5MB
var totalChunks = Math.ceil(file.size / chunkSize); //总分片数
var currentChunk = 0; //当前上传的分片序号
var reader = new FileReader();
reader.onload = function(e) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('X-Chunk-Number', currentChunk);
xhr.setRequestHeader('X-Total-Chunks', totalChunks);
xhr.onload = function() {
currentChunk++;
if (currentChunk < totalChunks) {
uploadChunk();
} else {
alert('File uploaded successfully!');
}
};
xhr.send(e.target.result);
};
function uploadChunk() {
var start = currentChunk * chunkSize;
var end = Math.min(start + chunkSize, file.size);
var chunk = file.slice(start, end);
reader.readAsArrayBuffer(chunk);
}
uploadChunk();
}
</script>
后端代码(Node.js + Express):
javascript
const express = require('express');
const app = express();
const fs = require('fs');
app.use(express.json());
app.post('/upload', (req, res) => {
const chunkNumber = req.headers['x-chunk-number'];
const totalChunks = req.headers['x-total-chunks'];
const fileStream = fs.createWriteStream('uploaded_file', { flags: 'a' });
req.pipe(fileStream);
if (chunkNumber == totalChunks - 1) {
fileStream.on('finish', () => {
res.sendStatus(200);
});
}
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
前端使用了HTML的<input type="file">
标签和JavaScript的FileReader
对象来实现分片读取文件,并通过XMLHttpRequest发送每个分片到后端。
后端使用Node.js和Express框架,接收到每个分片后将其写入到文件中,当收到最后一个分片时,触发finish
事件,表示文件上传完成。