需要手动调用上传接口的请驻足!!!
需求:图片数量限制最多 5 张,每张图片不得超过 10M。
1、el-upload 组件绑定的 :file-list 定义 fileList 单独维护。
2、定义 photoList 数组用来保存需要传给后端接口的数据。
3、此处上传图片事件是 on-change,并且加了 :auto-upload="false" 阻止自动上传文件。
<el-upload
:limit="5"
action="#"
list-type="picture-card"
:on-exceed="handleExceed"
v-model:file-list="fileList"
:on-change="uploadImg"
:auto-upload="false"
accept="image/jpg,image/jpeg,image/png,image/webp"
>
<el-icon><Plus /></el-icon>
<template #file="{ file }">
<div>
<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
<span class="el-upload-list__item-actions">
<span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
<el-icon><zoom-in /></el-icon>
</span>
<span class="el-upload-list__item-delete" @click="handleRemove(file)">
<el-icon><Delete /></el-icon>
</span>
</span>
</div>
</template>
<template #tip>
<div class="el-upload__tip"> 可以上传5张照片,单个不超过10M </div>
</template>
</el-upload>
// 预览弹窗
<el-dialog append-to-body v-model="dialogVisible">
<img width="100%" :src="state.dialogImageUrl" alt="" />
</el-dialog>
import { ElMessage, UploadUserFile } from 'element-plus';
let dialogVisible = ref(false);
let fileList: any = reactive<UploadUserFile[]>([]);
const state = reactive({
photoList: [],
dialogImageUrl: '',
})
// 上传文件
const uploadImg = (file) => {
// 单个文件大小不能超过50M
let fileSize = file.size / 1024;
let maxSize = 1024 * 10;
if (fileSize > maxSize) {
ElMessage({
message: '单个文件最大10M',
type: 'warning',
});
return;
}
let rawFile = file.raw;
let formData = new FormData();
formData.append('fileData', rawFile);
formData.append('fileType', 'testresultpic');
formData.append('workId', props.rowData.workId);
// 调用封装好的接口
uploadFile(formData).then((res) => {
ElMessage({
type: 'success',
message: '上传成功',
});
// 此处 res 的格式为{ fileName: '奥黛丽赫本', fileUrl: '/xxx' }
state.photoList.push(res);
});
};
// 删除
const handleRemove = (file) => {
const index = fileList.indexOf(file);
fileList.splice(index, 1);
state.photoList = state.photoList.filter((item) => item.fileName !== file.name);
};
// 预览
const handlePictureCardPreview = (file) => {
state.dialogImageUrl = file.url;
dialogVisible.value = true;
};
// 上传照片超出限制的提示
const handleExceed = () => {
ElMessage({
message: '最多上传5张照片',
type: 'warning',
});
};
有疑问的请留言。