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}`);
  });
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值