思路:通過<input type="file" id="file" name="file" />? ?<input type="button" id="breakPointUploadFile" name="breakPointUploadFile" />?獲取上傳的文件資源。調(diào)用Windows的分片對(duì)象File.prototype.slice弦讽。通過指定每次分片的大小污尉,計(jì)算出分片個(gè)數(shù)膀哲。然后采用遞歸的方式一直上傳每個(gè)分片至后臺(tái)。直到上傳分片數(shù)大于了總分片數(shù)時(shí)被碗,跳出遞歸某宪。具體代碼如下:
前端:
<input type="file" id="file" name="file" />
<input type="button" id="breakPointUploadFile" name="breakPointUploadFile" />
js代碼:
<script type="text/javascript">
//獲取文件分片對(duì)象
? ? const blobSlice =File.prototype.slice ||File.prototype.mozSlice ||File.prototype.webkitSlice;
$(function () {
//設(shè)置每個(gè)分片大小
? ? ? ? const chunkSize =2 *1024 *1024;// 每個(gè)chunk的大小,2兆
? ? ? ? $("#breakPointUploadFile").click(function () {
//得到上傳的文件資源
? ? ? ? ? ? const file =$('#file')[0].files[0];
// 需要分片成多少個(gè)
? ? ? ? ? ? const totalChunk =Math.ceil(file.size /chunkSize);
breakPointUploadFile(0,totalChunk,chunkSize,file);
});
});
/**
? ? * 分片上傳
? ? * i - 第幾片
? ? * totalChunk - 分片總數(shù)
? ? * chunkSize? - 每片大小
? ? * file 要上傳的文件
? ? * */
? ? function breakPointUploadFile(i, totalChunk, chunkSize, file) {
//當(dāng)前上傳文件塊的起始位置
? ? ? ? ? ? const startLength = i * chunkSize;
//當(dāng)文件末尾不足一個(gè)分片時(shí)锐朴,取小者
? ? ? ? ? ? const endLength =Math.min(file.size,startLength + chunkSize);
var formData =new FormData();
//通過blobSlice獲取分片文件
? ? ? ? ? ? formData.append("file",blobSlice.call(file,startLength,endLength));
formData.append("startLength",startLength);
formData.append("fileName", file.name);
$.ajax({
url:'http://localhost:8080/breakPointUploadFileDo',
dataType:'json',
type:'POST',
async:false,
data:formData,
processData:false,
contentType:false,
success:function (data) {
console.log(data);
if (data.succeed) {
i++;
//當(dāng)分片上傳達(dá)到總分片個(gè)數(shù)兴喂,跳出遞歸
? ? ? ? ? ? ? ? ? ? ? ? if (i < totalChunk) {
console.log("****>" + i);
setTimeout(function () {
//采用遞歸調(diào)用該函數(shù)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? breakPointUploadFile(i, totalChunk, chunkSize, file);
},0);
}else {
alert("文件上傳成功");
}
}
},
error:function (response) {
console.log(response);
alert("異常")
}
});
}
</script>
代碼截圖:
后臺(tái)代碼:
@RequestMapping("breakPointUploadFileDo")
public AjaxResponse breakPointUploadFileDo(@RequestParam MultipartFile file,long startLength, String fileName) {
AjaxResponse ajaxResponse =new AjaxResponse(true,"200");
System.out.println(file +" ** " + startLength);
if (file.getSize() <=0) {
return new AjaxResponse(false,"500");
}
int len =0;
final byte[] arr =new byte[1024];
final String writeFileName ="D:/test-" + fileName;
try (RandomAccessFile writeFile =new RandomAccessFile(writeFileName,"rw")) {
writeFile.seek(startLength);
final InputStream iStream = file.getInputStream();
while ((len = iStream.read(arr)) != -1) {
writeFile.write(arr,0, len);
}
}catch (final Exception e) {
e.printStackTrace();
}
return ajaxResponse;
}