松鼠的博客

导航

js实现大文件分片上传

简单的实现一个分片上传

// 设置分片大小(大小根据需求调整)
const CHUNK_SIZE = 1024 * 1024; // 1MB

// 选择文件并切割成分片
const fileInput = document.getElementById('file-input');
const chunks = [];
let currentChunkIndex = 0;

fileInput.addEventListener('change', handleFileInputChange);

function handleFileInputChange(event) {
const file = event.target.files[0];
splitFileIntoChunks(file);
uploadFileChunks();
}

function splitFileIntoChunks(file) {
const totalChunks = Math.ceil(file.size / CHUNK_SIZE);

for (let i = 0; i < totalChunks; i++) {
const start = i * CHUNK_SIZE;
const end = start + CHUNK_SIZE;
const chunk = file.slice(start, end);
chunks.push(chunk);
console.log('chunk',chunk,chunks);
}
}
// 上传分片
function uploadFileChunks() {
if (currentChunkIndex >= chunks.length) {
console.log('All chunks uploaded!');
return;
}

const formData = new FormData();
formData.append('chunk', chunks[currentChunkIndex]);
// 第几片
formData.append('index', currentChunkIndex);
// 总片数
formData.append('totalChunks', chunks.length);

// 使用 XMLHttpRequest 或 Fetch API 进行异步上传分片
// 在每个请求的回调函数中继续上传下一个分片

// 示例使用 Fetch API 发送请求
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
if(currentChunkIndex === chunks.length - 1){
console.log('Uploaded all chunks!');
}else{
currentChunkIndex++;
uploadFileChunks(); // 继续上传下一个分片
}
} else {
console.log('Chunk upload failed.');
}
})
.catch(error => {
console.log(`Error uploading chunk: ${error}`);
});
}

 

参考文章:http://blog.ncmem.com/wordpress/2023/11/14/js%e5%ae%9e%e7%8e%b0%e5%a4%a7%e6%96%87%e4%bb%b6%e5%88%86%e7%89%87%e4%b8%8a%e4%bc%a0/

欢迎入群一起讨论

 

 

posted on 2023-11-14 10:07  Xproer-松鼠  阅读(24)  评论(0编辑  收藏  举报