前端大文件如何切片上传---简易版

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="file" name="" id="fileInput">
    <button onclick="uploadFile()">upload</button>
</body>
<script>
    const chunk_size=5*1024*1024;//每块大小为5m
    function uploadFile(){
        const file=document.getElementById('fileInput').files[0];
        if(!file){
            console.log('还没有选择文件')
            return;
        }
        const total_chunks=Math.ceil(file.size/chunk_size);
        let current_chunk_index=0;
        function uploadChunk(){
            if(current_chunk_index>=total_chunks){
                console.log('上传完成了');
                return
            }
            const start=current_chunk_index*chunk_size;
            const end=Math.min(start+chunk_size,file.size);
            const chunk=file.slice(start,end);
            const fordata=new FormData();
            fordata.append('file',chunk);
            fordata.append('chunkNumber',current_chunk_index+1);
            fordata.append('totalChunks',total_chunks);
            fetch('url',{
                method:"POST",
                body:fordata
            }).then(res=>{
                if(res.ok){
                    current_chunk_index++;
                    uploadChunk()
                }
            }).catch(e=>{
                console.log('上传出错')
            })

        }
        uploadChunk();
    }
</script>
<script>

    /*
常见问题:
1、网络断开,之前上传的没了
2、传着传着,网络波动,啥都没了
3、关机想接着传,做不到
*/


/**
 * 专业术语:
 * -断点续传
 * -断开重连重传
 * -切片上传
 */

/**
 * 方案
 * -前端切片
 * -将切片传递给后端
 * -后端组合切片
 */


/**
 * web-worker多线程切片,处理完成交给主线程发送
 * 
 */
</script>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值