<template>
<div>
<input type="file" @change="fileEvent" />
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
size: 1 * 1024 * 1024,//每片的大小
};
},
methods: {
fileEvent(e) {
let fileArr = this.sliceFile(e.target.files[0]);//获取到文件
let fileName = e.target.files[0].name;//保存文件名称
fileArr.forEach((e, i) => {//循环每片
let data = new FormData();//创建formdata对象
data.append("file", new File([e],fileName));//添加进去
data.append("totalNumber", fileArr.length)
data.append("chunkNumber", i)
this.uploadFile(data);
})
},
sliceFile(file) {
const chunks = [];
let start = 0;
let end;
while (start < file.size) {
end = Math.min(start + this.size, file.size);
chunks.push(file.slice(start, end));
console.log(file.slice(start, end));
console.log(start, end);
start = end;
}
return chunks;
},
//上传
uploadFile(data) {
axios.post("http://192.168.3.4:8081/file/upload", data)
.then(() => {}).catch((error) => {
console.error("文件上传失败", error);
});
},
},
};
</script>
参考文章:http://blog.ncmem.com/wordpress/2023/10/09/js实现分片上传文件/