感觉el-upload自定义也没合适的文档,想自定义处理事件和处理文件的时候不方便。所以研究了一下。
首先给出基本操作:
// vue中定义了上传的变量
const uploadFile = ref(null)
// 下面这个是可以显示具体有哪些操作
console.log(uploadFile.value)
uploadFile.value.abort(); // 取消上传
uploadFile.value.submit(); // 提交上传
uploadFile.value.clearFiles(); // 清空文件列表
uploadFile.value.handleStart(file); // 开始上传指定的文件
uploadFile.value.handleRemove(file); // 移除指定的文件
给出完整的代码:
?
<template>
<el-scrollbar class="upload-file" min-size="100">
<el-upload
ref="uploadFile"
:multiple="true"
:on-change="handleChange"
:on-remove="handleRemove"
class="left-view"
:auto-upload="false"
accept=".gjf,.mol"
>
<template #trigger>
<el-button type="primary">选择文件</el-button>
</template>
<template #tip>
<div class="el-upload__tip text-red">
</div>
</template>
</el-upload>
</el-scrollbar>
</template>
<script setup>
import {ref} from 'vue'
const uploadFile = ref(null)
const handleChange = async (file, uploadFileRef) => {
/*
console.log(uploadFile.value)
uploadFile.value.abort(); // 取消上传
uploadFile.value.submit(); // 提交上传
uploadFile.value.clearFiles(); // 清空文件列表
uploadFile.value.handleStart(file); // 开始上传指定的文件
uploadFile.value.handleRemove(file); // 移除指定的文件
*/
const allowedExtensions = ['gjf', 'mol'];
if (!allowedExtensions.includes(file.name.split('.')[1])) {
ElMessage.error('只能上传Gjf或者mol格式的文件');
// uploadFile.value.clearFiles()
uploadFile.value.handleRemove(file);
} else {
// 保存文件内容
fileList.push(file);
}
}
watch(fileList, async (newVal, oldVal) => {
// 等待500毫秒,以确保 fileList 变化稳定
await new Promise(resolve => setTimeout(resolve, 500));
// 清空 srcList 数组
srcList.splice(0, srcList.length);
// 使用 Object.keys() 遍历 fileList 的属性
for (const key of Object.keys(newVal)) {
const file = newVal[key];
await showFileToImage(file);
}
});
// 处理移除文件时候的操作
const handleRemove = async (file, fileList) => {
let uid = file.uid
const index = srcList.findIndex((file) => file.uid === uid);
if (index > -1) {
srcList.splice(index, 1);
}
}
const showFileToImage = async (file) => {
let reader = new FileReader();
reader.readAsArrayBuffer(file.raw);
return new Promise(resolve => {
reader.onload = async function (event) {
let image_data;
if (file.name.split('.')[1].toLowerCase() === 'gjf') {
// gjf转图片
image_data = await ConvertFile2Image(reader.result, "gjf");
} else if (file.name.split('.')[1].toLowerCase() === 'mol') {
// mol转图片
image_data = await ConvertFile2Image(reader.result, "mol");
}
let imageURL = 'data:image/png;base64,' + image_data.data.image_data;
srcList.push({name: file.name, uid: file.uid, url: [imageURL]});
resolve();
};
});
}
</script>