大文件分片上传

<input type="file" id="largeFile">
<button onclick="startUpload()">开始上传</button>
<div id="progressBar"></div>

<script>
async function startUpload() {
  const file = document.getElementById('largeFile').files[0];
  if (!file) return;
  
  // 配置参数
  const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB分片
  const TOTAL_CHUNKS = Math.ceil(file.size / CHUNK_SIZE);
  const FILE_ID = `${file.name}-${file.size}-${Date.now()}`;
  
  // 创建进度跟踪器
  const uploadedChunks = new Set();
  
  // 并行上传控制(最大5并发)
  const parallelLimit = 5;
  let currentUploads = 0;
  let activeChunks = 0;
  
  for (let chunkIndex = 0; chunkIndex < TOTAL_CHUNKS; ) {
    if (currentUploads >= parallelLimit) {
      await new Promise(resolve => setTimeout(resolve, 500));
      continue;
    }
    
    if (uploadedChunks.has(chunkIndex)) {
      chunkIndex++;
      continue;
    }
    
    currentUploads++;
    activeChunks++;
    
    const start = chunkIndex * CHUNK_SIZE;
    const end = Math.min(start + CHUNK_SIZE, file.size);
    const chunk = file.slice(start, end);
    
    uploadChunk(chunk, chunkIndex, FILE_ID, TOTAL_CHUNKS, file.name)
      .then(() => {
        uploadedChunks.add(chunkIndex);
        updateProgress(uploadedChunks.size, TOTAL_CHUNKS);
      })
      .catch(err => console.error(`分片${chunkIndex}失败:`, err))
      .finally(() => {
        currentUploads--;
        activeChunks--;
      });
    
    chunkIndex++;
  }
  
  // 检查所有分片完成
  const checkCompletion = setInterval(() => {
    if (activeChunks === 0 && uploadedChunks.size === TOTAL_CHUNKS) {
      clearInterval(checkCompletion);
      completeUpload(FILE_ID, file.name);
    }
  }, 1000);
}

async function uploadChunk(chunk, index, fileId, total, filename) {
  const formData = new FormData();
  formData.append('file', chunk, filename);
  formData.append('chunkIndex', index);
  formData.append('totalChunks', total);
  formData.append('fileId', fileId);
  
  return fetch('/api/upload/chunk', {
    method: 'POST',
    body: formData
  }).then(res => {
    if (!res.ok) throw new Error('上传失败');
    return res.json();
  });
}

async function completeUpload(fileId, filename) {
  return fetch('/api/upload/merge', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ fileId, filename })
  }).then(res => {
    if (res.ok) alert('上传成功!');
    else alert('合并失败');
  });
}

function updateProgress(done, total) {
  const percent = Math.round((done / total) * 100);
  document.getElementById('progressBar').innerHTML = `
    <div style="width: ${percent}%; background: #4CAF50; height: 20px;">
      ${percent}%
    </div>
  `;
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猛男敲代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值