<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
<input type="text" id="fileInput" />
<button onclick="uploadFile()">Upload</button>
<script>
const CHUNK_SIZE = 5 * 1024 * 1024; // 每一块为5m
function uploadFile() {
const file = document.getElementById("fileInput")[0];
if (!file) {
alert("please select a file");
return;
}
const totalChunk = Math.ceil(file.size / CHUNK_SIZE);
let currentChunk = 0;
function uoloadChunk() {
if (currentChunk >= totalChunk) {
alert('upload complete')
return;
}
const start=currentChunk*CHUNK_SIZE
const end=Math.min(start + CHUNK_SIZE,file.size)
const chunk=file.slice(start,end)
const formData=new FormData()
formData.append('file',chunk)
formData.append('chunkNumber',currentChunk+1)
formData.append('totalCHunks',totalChunk)
fetch('/upload',{
method:'POST',
body:formData
}).then(response=>{
if(response.ok){
currentChunk++
uploadChunk()
}else{
console.log('chunk upload failed')
}
}).catch(error=>{
console.log('upload error',error)
})
}
uploadChunk()
}
</script>
</body>
</html>