slice large file into chunks and upload using ajax and html5 FileReader

前端 未结 3 1898
借酒劲吻你
借酒劲吻你 2020-12-14 21:52

What I want to implement is:

In the front end, I use the html5 file api to read the file, and then upload the file\'s content to the php backend using ajax, and it\'

3条回答
  •  执念已碎
    2020-12-14 22:16

    There is a small error in your js script I noticed that the reader.onprogress event is triggered more times than the xhr load event. In this case some chunks are skipped. Try to increment the loaded variable inside the load function.

    function uploadFile(file){
    var loaded = 0;
    var step = 1024*1024;
    var total = file.size;
    var start = 0;
    var progress = document.getElementById(file.name).nextSibling.nextSibling;
    
    var reader = new FileReader();
    
    reader.onload = function(e){
            var xhr = new XMLHttpRequest();
            var upload = xhr.upload;
            upload.addEventListener('load',function(){
            loaded += step;
            progress.value = (loaded/total) * 100;
                    if(loaded <= total){
                            blob = file.slice(loaded,loaded+step);
    
                            reader.readAsBinaryString(blob);
                    }else{
                            loaded = total;
                    }
            },false);
            xhr.open("POST", "upload.php?fileName="+file.name+"&nocache="+new Date().getTime());
            xhr.overrideMimeType("application/octet-stream");
            xhr.sendAsBinary(e.target.result);
    };
    var blob = file.slice(start,step);
    reader.readAsBinaryString(blob); }
    

提交回复
热议问题