文件分块+断点续传 实现大文件上传全栈解决方案(前端+nodejs)
前端代码实现文件分块并使用FormData发送给Node.js服务器,服务器端接收文件块并写入磁盘,最后合并文件块。
// 前端JavaScript代码
// 文件分块上传函数
function uploadFileInChunks(file, chunkSize = 1024 * 1024, uploadUrl) {
let fileSize = file.size;
let chunkCount = Math.ceil(fileSize / chunkSize);
let start = 0;
let end = chunkSize;
for (let i = 0; i < chunkCount; i++) {
let chunk = file.slice(start, end);
let formData = new FormData();
formData.append('file', chunk);
formData.append('filename', file.name);
formData.append('chunkIndex', i);
formData.append('chunkCount', chunkCount);
fetch(uploadUrl, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
console.log('Chunk uploaded successfully');
} else {
console.error('Error uploading chunk');
}
})
.catch(error => console.error('Error:', error));
start = end;
end = start + chunkSize;
}
}
// 使用示例
const inputElement = document.getElementById('fileInput');
inputElement.addEventListener('change', function(e) {
const file = e.target.files[0];
const uploadUrl = 'http://yourserver.com/upload'; // Node.js服务器地址
uploadFileInChunks(file, 1024 * 1024, uploadUrl); // 每个块大小为1MB
});
Node.js服务器端代码:
// Node.js + Express代码
const express = require('express');
const fs = require('fs');
const multer = require('multer');
const path = require('path');
const app = express();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
let folder = 'uploads/' + req.body.filename;
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder, { recursive: true });
}
cb(null, folder)
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + req.body.chunkIndex)
}
})
const upload = multer({ storage: storage });
app.post('/upload', upload.single('file'), function (req, res) {
let fileIndex = req.body.chunkIndex;
let fileName = req.body.filename;
let chunkCount = req.body.chunkCount;
let fileChunk = req.file.path;
// 合并文件逻辑(简化版)
if (checkIfAllChunksPresent(fileName, chunkCount)) {
conc
评论已关闭