大文件上传实现

分片上传

  1. 将大文件分割成多个小片(chunk),逐个上传。
  2. 每个片上传成功后,服务器可以返回确认信息。
  3. 所有片上传完成后,服务器端将这些片重新组合成原始文件。

以下是一个简单的分片上传的前端实现示例:

function uploadFile(file) {
    const CHUNK_SIZE = 1 * 1024 * 1024; // 1MB
    let currentChunk = 0;
    const totalChunks = Math.ceil(file.size / CHUNK_SIZE);

    function uploadChunk() {
        const start = currentChunk * CHUNK_SIZE;
        const end = Math.min(file.size, start + CHUNK_SIZE);
        const chunk = file.slice(start, end);

        const formData = new FormData();
        formData.append('file', chunk);
        formData.append('fileName', file.name);
        formData.append('chunkIndex', currentChunk);
        formData.append('totalChunks', totalChunks);

        fetch('/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentChunk++;
                if (currentChunk < totalChunks) {
                    uploadChunk(); // 递归上传下一片
                } else {
                    console.log('上传完成');
                }
            } else {
                console.error('上传失败', data.message);
            }
        })
        .catch(error => {
            console.error('上传错误', error);
        });
    }

    uploadChunk();
}

在服务器端,你需要处理接收到的片,存储这些片,并在所有片都上传完成后将它们合并。具体的服务器端实现取决于你使用的后端技术栈。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值