<template>
<el-upload ref="uploadRef" class="upload-demo" action="" :auto-upload="false" :show-file-list="false"
:http-request="handleUploadRequest" :before-upload="handleBeforeUpload">
<template #trigger>
<el-button type="primary">选择文件</el-button>
</template>
<el-button class="ml-3" type="success" @click="submitUpload">
上传文件{{ progressNum }}
</el-button>
<template #tip>
<div class="el-upload__tip">
文件大小限制 500kb
</div>
</template>
</el-upload>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import type { UploadInstance } from 'element-plus';
const uploadRef = ref<UploadInstance>();
// 文件对象
const fileValue = ref<File | null>(null);
// 分片大小
const chunkSize = ref<number>(1024 * 1024);
// 总分片数量
const totalChunks = ref<number>(0);
// 当前分片索引
const currentChunk = ref<number>(0);
// 进度条值
const progressNum = ref<number>(0);
// 设置beforeUpload钩子函数以获取选中的文件
const handleBeforeUpload = (file: File) => {
console.log(file, '-00-0-0-11111');
fileValue.value = file;
handleFileChange(file);
return false; // 阻止默认上传行为,因为我们使用自定义的http-request
};
// 在选择文件后计算总分片数
const handleFileChange = (file: File) => {
console.log(file, '-0-0-0-0');
if (!file) return;
totalChunks.value = Math.ceil(file.size / chunkSize.value);
};
// 提交上传
const submitUpload = () => {
uploadRef.value!.submit()
if (fileValue.value) {
currentChunk.value = 0;
handleUploadRequest();
}
};
// 自定义上传请求方法
const handleUploadRequest = async () => {
if (!fileValue.value || currentChunk.value >= totalChunks.value) return;
const start = currentChunk.value * chunkSize.value;
const end = Math.min(fileValue.value.size, start + chunkSize.value);
const chunk = fileValue.value.slice(start, end);
const formData = new FormData();
formData.append('file', chunk as Blob);
formData.append('chunk', currentChunk.value.toString());
formData.append('totalChunks', totalChunks.value.toString());
formData.append('fileName', fileValue.value.name);
if (true) {
// 更新当前分片索引和进度
currentChunk.value++;
progressNum.value = (currentChunk.value / totalChunks.value) * 100;
// 如果所有分片都已上传,则触发最终的完成逻辑(此处仅作示例,实际应用中根据服务器返回进行处理)
if (currentChunk.value === totalChunks.value) {
console.log('全部分片已上传完成');
}
} else {
console.error('Error uploading chunk');
}
};
</script>
element-ui大文件上传 单个文件
于 2024-02-26 15:45:52 首次发布