jq php 大文件切片上传实现方法核心代码

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>upload</title>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <style>
        #jindu{height: 40px;width: 0;background: #666;text-align: center;line-height: 40px;color: #fff}
    </style>
</head>
<body>
    <input type="file" name="file" id="file">
    <button id="upload" onClick="upload()">upload</button>
    <div id="jindu"></div>
    <p>文件切片上传,每次4MB</p>
    <script type="text/javascript">
        var bytesPerPiece = 1024 * 1024*4; // 每个文件切片大小定为4MB .
        var totalPieces;
        var jindu = document.getElementById("jindu");

        //发送请求
        function upload() {
            var blob = document.getElementById("file").files[0];
            var start = 0;
            var end;
            var index = 0;
            var filesize = blob.size;
            var filename = blob.name;

            //计算文件切片总数
            totalPieces = Math.ceil(filesize / bytesPerPiece);
            function doup(){
                end = start + bytesPerPiece;
                var chunk = blob.slice(start,end);//切割文件    
                var formData = new FormData();
                formData.append("file", chunk, filename);
                formData.append("index", index);
                $.ajax({
                    url: './upload.php',
                    type: 'POST',
                    cache: false,
                    data: formData,
                    processData: false,
                    contentType: false,
                    success:function(){

                        start = end;
                        if(start < filesize){
                             index++;
                             var jindusize = ((index+1)/totalPieces)*100;
                             jindu.style.width=jindusize+"%";
                             jindu.innerHTML = Math.floor(jindusize)+"%";
                            doup();
                        }else{
                            jindu.style.width="100%";
                            jindu.innerHTML = "100%";
                        }
                        
                    }
                });

           }
           doup();
        }
    </script>
</body>
</html>

后端

<?php
header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
$file = $_FILES['file'];
$filename = $file['name'];
file_put_contents("./upload/".mb_convert_encoding($filename,"GBK","UTF-8"), file_get_contents($file['tmp_name']), FILE_APPEND);

代码只有核心功能,并不完善,使用时需要根据自己业务修改

posted @ 2020-03-12 00:53  MasterC  阅读(628)  评论(0编辑  收藏  举报