<template>
<div>
<input
type="file"
@change="handleFileChange"
/>
<el-button @click="handleUpload">上传</el-button>
</div>
</template>
<script>
const SIZE = 10 * 1024; // 切片大小
export default {
data: () => ({
container: {
file: null
},
data: []
}),
methods: {
request () { },
handleFileChange (e) {
// this.container.file
const [file] = e.target.files
this.container.file = file;
},
// 生成文件切片
createFileChunk (file, size = SIZE) {
const fileChunkList = [];
let cur = 0;
while (cur < file.size) {
fileChunkList.push({ file: file.slice(cur, cur + size) });
cur += size;
}
return fileChunkList;
},
// 上传切片
async uploadChunks () {
const requestList = this.data
.map(({ chunk, hash }) => {
const formData = new FormData();
formData.append("chunk", chunk);
formData.append("hash", hash);
formData.append("filename", this.container.file.name);
return { formData };
})
.map(async ({ formData }) =>
this.request({
url: "http://localhost:3000",
data: formData
})
);
await Promise.all(requestList); // 并发切片
await this.mergeRequest() // 合并切片
},
// 合并切片
async mergeRequest() {
await this.request({
url: "http://localhost:3000/merge",
headers: {
"content-type": "application/json"
},
data: JSON.stringify({
filename: this.container.file.name
})
});
},
async handleUpload () {
// if (!this.container.file) return;
const fileChunkList = this.createFileChunk(this.container.file);
this.data = fileChunkList.map(({ file }, index) => ({
chunk: file,
hash: this.container.file.name + "-" + index // 文件名 + 数组下标
}));
await this.uploadChunks();
}
}
};
</script>
Vue切片上传
最新推荐文章于 2025-10-21 21:26:57 发布
本文介绍了如何在Vue.js应用中实现文件的切片上传功能,通过JavaScript的File API进行文件切割,然后逐片发送到服务器,以提高大文件上传的效率和用户体验。
3417

被折叠的 条评论
为什么被折叠?



