Js method to achieve large slices of the file upload large files js implementation slices upload

Js method to achieve large file uploads slices

Js Blob object by the object may be achieved FormData large pieces of the file upload function, on the specific use FormData Blob and to the following address can view the
use FormData objects
using Blob object
The following codes are implemented, in this embodiment the rear end of the code use php to achieve, is to demonstrate the basic functions of specific validation logic to ignore some files.
Preceding the code:

Copy the code
<!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>
</head>
<body>
    <input type="file" name="file" id="file">
    <button id="upload" onClick="upload()">upload</button>
    <script type="text/javascript">
        var bytesPerPiece = 1024 * 1024; // 每个文件切片大小定为1MB .
        var totalPieces;
        //发送请求
        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);
            while(start < filesize) {
                end = start + bytesPerPiece;
                if(end > filesize) {
                    end = filesize;
                }

                var chunk = blob.slice(start,end);//切割文件    
                var sliceIndex= blob.name + index;
                var formData = new FormData();
                formData.append("file", chunk, filename);
                $.ajax({
                    url: 'http://localhost:9999/test.php',
                    type: 'POST',
                    cache: false,
                    data: formData,
                    processData: false,
                    contentType: false,
                }).done(function(res){ 

                }).fail(function(res) {

                });
                start = end;
                index++;
            }
        }
    </script>
</body>
</html>
Copy the code

 

Guess you like

Origin www.cnblogs.com/yuanjiangw/p/12000206.html