js實現大檔案分片上傳的方法
阿新 • • 發佈:2019-02-19
<input type="file" name="file" id="file">
<button id="upload" onClick="upload()">upload</button>
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++; } }