前端大文件分断上传
function upload() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const chunkSize = 1024 * 1024; // 每个分片的大小,这里设置为1MB
const totalChunks = Math.ceil(file.size / chunkSize); // 总分片数
let currentChunk = 0; // 当前上传的分片
// 读取并上传分片
function uploadChunk(start, end) {
const chunk = file.slice(start, end);
const formData = new FormData();
formData.append('file', chunk);
formData.append('chunk', currentChunk);
formData.append('chunks', totalChunks);
// 发送POST请求上传分片
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
// 继续上传下一个分片
currentChunk++;
if (currentChunk < totalChunks) {
const start = currentChunk * chunkSize;
const end = start + chunkSize;
uploadChunk(start, end);
} else {
console.log('文件上传完成');
}
} else {
console.log('上传失败');
}
})
.catch(error => {
console.error('上传出错', error);
});
}
// 开始上传第一个分片
const start = currentChunk * chunkSize;
const end = start + chunkSize;
uploadChunk(start, end);
}