代码拉取完成,页面将自动刷新
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>大文件上传</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.js"></script>
</head>
<body>
<form action="" id="FormUpload">
<p id="percent">上传进度 0%</p>
<input type="file" id="inputUpload" />
<button type="submit">提交</button>
</form>
<script>
const form = document.getElementById('FormUpload')
const ipt = document.getElementById('inputUpload')
let file // 待上传的文件
let uploadPercent = 0 // 上传进度百分比
ipt.addEventListener('change', function (e) {
file = e.target.files[0]
})
form.addEventListener('submit', async function (e) {
e.preventDefault()
let size = 2 * 1024 * 1024 // 设置切片大小 2M
let fileSize = file.size // 文件大小
// 分多少块切片
let totalChunks = Math.ceil(fileSize / size)
for (let i = 0; i < totalChunks; i++) {
let start = i * size
let end = Math.min(start + size, fileSize)
let chunk = file.slice(start, end) // 待上传的切片文件
let formData = new FormData()
formData.append('file', chunk)
formData.append('chunkIndex', i)
formData.append('totalChunks', totalChunks)
// 向后端发送请求
await axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
},
//axios提供的监测请求进度的api
onUploadProgress: function (progressEvent) {
uploadPercent = Math.round((progressEvent.loaded / progressEvent.total) * 100)
document.getElementById('percent').textContent = `上传进度 ${uploadPercent}%`
}
})
}
})
</script>
</body>
</html>
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。