0
点赞
收藏
分享

微信扫一扫

js实现大文件分片上传

一葉_code 2023-11-30 阅读 56

简单的实现一个分片上传

// 设置分片大小(大小根据需求调整)
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实现大文件分片上传/



 

举报

相关推荐

0 条评论