修复多图上传无法预览已上传的文件

修复多图上传无法预览已上传的文件
This commit is contained in:
2025-11-27 14:49:14 +08:00
parent 2a06244639
commit 928e82f557

View File

@@ -1,112 +1,135 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useVModel } from '@vueuse/core';
import { Modal, Upload } from 'ant-design-vue'; import { Modal, Upload } from 'ant-design-vue';
import type { UploadFile } from 'ant-design-vue';
// 恢复使用原有的上传接口
import { uploadFile } from '#/api/core/upload'; import { uploadFile } from '#/api/core/upload';
import { Icon } from '#/components/icon'; import { Icon } from '#/components/icon';
defineOptions({ // 定义接口
name: 'UploadImage', interface FileItem {
inheritAttrs: false, uid: string;
name: string;
status: 'uploading' | 'done' | 'error';
url: string;
}
// 定义props
interface Props {
modelValue: string[];
multiple?: boolean;
maxCount?: number;
}
const props = withDefaults(defineProps<Props>(), {
modelValue: () => [],
multiple: true,
maxCount: 9,
}); });
const props = defineProps({ const emit = defineEmits<{
modelValue: { 'update:modelValue': [value: string[]];
type: Array as () => string[], }>();
default: () => [],
},
multiple: {
type: Boolean,
default: true,
},
maxCount: {
type: Number,
default: 9,
},
});
const emits = defineEmits(['update:modelValue']); const fileList = ref<FileItem[]>([]);
const mValue = useVModel(props, 'modelValue', emits, { // 初始化fileList
passive: true, const initFileList = () => {
}); fileList.value = props.modelValue.map((url) => ({
const fileList = ref(
props.modelValue.map((url) => ({
uid: url, uid: url,
name: url.split('/').pop() || 'file', name: url.split('/').pop() || 'file',
status: 'done', status: 'done' as const,
url,
})),
);
// 监听 modelValue 变化,同步到 fileList
watch(props.modelValue, (newVal) => {
fileList.value = newVal.map((url) => ({
uid: url,
name: url.split('/').pop() || 'file',
status: 'done',
url, url,
})); }));
}); };
// 监听 fileList 变化,同步到 modelValue // 初始化
watch(fileList, (newVal) => { initFileList();
mValue.value = newVal
// 监听外部modelValue变化,同步到fileList
watch(() => props.modelValue, (newVal) => {
const currentUrls = fileList.value.filter(file => file.status === 'done').map(file => file.url);
if (JSON.stringify(newVal) !== JSON.stringify(currentUrls)) {
fileList.value = newVal.map((url) => ({
uid: url,
name: url.split('/').pop() || 'file',
status: 'done' as const,
url,
}));
}
}, { deep: true });
// 统一通过updateModelValue函数更新modelValue
const updateModelValue = () => {
const urls = fileList.value
.filter((file) => file.status === 'done' && file.url) .filter((file) => file.status === 'done' && file.url)
.map((file) => file.url); .map((file) => file.url);
}); emit('update:modelValue', urls);
};
// 使用原有的uploadFile接口
const customRequest = async (options: any) => {
const { file, onProgress, onSuccess, onError } = options;
// 创建上传中的文件项
const uploadingFile: FileItem = {
uid: file.uid,
name: file.name,
status: 'uploading',
url: '',
};
fileList.value = [...fileList.value, uploadingFile];
const customRequest = async (e: any) => {
try { try {
// 使用原有的uploadFile接口
const res = await uploadFile({ const res = await uploadFile({
file: e.file, file: file,
}); });
// 更新 fileList // 更新文件状态为完成
fileList.value = [ const updatedFileList = fileList.value.map(item =>
...fileList.value.filter((file) => file.status !== 'uploading'), item.uid === file.uid
{ ? { ...item, status: 'done' as const, url: res.url }
uid: res.url, : item
name: e.file.name, );
status: 'done',
url: res.url,
},
];
// 更新 modelValue fileList.value = updatedFileList;
mValue.value = fileList.value.map((file) => file.url); updateModelValue();
onSuccess(res);
// 触发上传完成回调
e.onSuccess?.(res);
} catch (error) { } catch (error) {
console.error('上传失败', error); console.error('上传失败', error);
e.onError?.(error); // 更新文件状态为错误
const updatedFileList = fileList.value.map(item =>
item.uid === file.uid
? { ...item, status: 'error' as const }
: item
);
fileList.value = updatedFileList;
onError(error);
} }
}; };
const handleRemove = (file: any) => { // 处理文件删除
// 从 fileList 中移除 const handleRemove = (file: UploadFile) => {
fileList.value = fileList.value.filter((item) => item.uid !== file.uid); fileList.value = fileList.value.filter((item) => item.uid !== file.uid);
updateModelValue();
// 更新 modelValue
mValue.value = fileList.value.map((file) => file.url);
}; };
// 预览功能
const previewVisible = ref(false); const previewVisible = ref(false);
const previewImage = ref(''); const previewImage = ref('');
const previewTitle = ref(''); const previewTitle = ref('');
const handlePreview = async (file) => { const handlePreview = async (file: UploadFile) => {
previewImage.value = file.response.url || file.preview; previewImage.value = file.url || '';
previewVisible.value = true; previewVisible.value = true;
previewTitle.value = previewTitle.value = file.name || file.url?.split('/').pop() || '';
file.name || file.url.slice(Math.max(0, file.url.lastIndexOf('/') + 1));
}; };
// 计算是否还能上传更多图片 // 计算是否显示上传按钮
const showUploadButton = computed(() => const showUploadButton = computed(() =>
props.multiple props.multiple
? fileList.value.length < props.maxCount ? fileList.value.length < props.maxCount
@@ -115,55 +138,39 @@ const showUploadButton = computed(() =>
</script> </script>
<template> <template>
<Upload <div>
v-model:value="fileList" <Upload
:custom-request="customRequest" :file-list="fileList"
:multiple="multiple" :custom-request="customRequest"
:limit="maxCount" :multiple="multiple"
:show-upload-list="{ showPreviewIcon: true, showRemoveIcon: true }" :max-count="maxCount"
list-type="picture-card" :show-upload-list="{
@remove="handleRemove" showPreviewIcon: true,
@preview="handlePreview" showRemoveIcon: true,
> }"
<div v-if="showUploadButton" class="upload-button"> list-type="picture-card"
<Icon icon="ant-design:plus-outlined" /> @remove="handleRemove"
<div class="ant-upload-text">上传图片</div> @preview="handlePreview"
</div> >
</Upload> <div v-if="showUploadButton" class="upload-button">
<Modal <!-- 恢复使用Icon组件 -->
v-model:visible="previewVisible" <Icon icon="ant-design:plus-outlined" />
:title="previewTitle" <div class="ant-upload-text">上传图片</div>
footer="" </div>
width="60%" </Upload>
>
<img alt="example" style="width: 100%" :src="previewImage" /> <Modal
</Modal> v-model:visible="previewVisible"
:title="previewTitle"
footer=""
width="60%"
>
<img alt="预览图片" style="width: 100%" :src="previewImage" />
</Modal>
</div>
</template> </template>
<style lang="less" scoped> <style lang="less" scoped>
.m-avatar-wrap {
position: relative;
height: 102px;
width: 102px;
.m-avatar-icon-delete {
position: absolute;
top: 0;
right: 0;
cursor: pointer;
opacity: 0;
transition: opacity 0.3s;
background-color: rgba(0, 0, 0, 0.5);
color: white;
border-radius: 0 0 0 4px;
padding: 2px 4px;
}
&:hover .m-avatar-icon-delete {
opacity: 1;
}
}
.upload-button { .upload-button {
display: flex; display: flex;
flex-direction: column; flex-direction: column;