js - 大文件上传
分片上传
分片上传的好处是将一个大请求分成多个小请求来执行,这样当其中一些请求失败后,不需要重新上传整个文件,而只需要上传失败的分片就可以了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>upload</title>
</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);
console.log('blob:',blob)
console.log('totalPieces:',totalPieces)
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);
console.log('start:',start)
console.log('end:',end)
console.log('chunk:',chunk)
console.log('sliceIndex:',sliceIndex)
console.log('formData:',formData)
// $.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>
参考地址
https://www.cnblogs.com/songsu/p/11527655.html
https://www.cnblogs.com/sghy/p/9143955.html
https://blog.csdn.net/weixin_45525177/article/details/103729551