92 lines
2.4 KiB
Vue
92 lines
2.4 KiB
Vue
<template>
|
|
<n-upload
|
|
:list-type="listType"
|
|
:file-list="fileList"
|
|
:max="max"
|
|
:accept="accept"
|
|
:custom-request="doUpload"
|
|
@remove="onRemove"
|
|
>
|
|
<template v-if="listType === 'image-card'">
|
|
<div class="upd-trigger">
|
|
<n-icon :component="AddOutline" :size="22" />
|
|
<span>{{ t('common.action.upload') }}</span>
|
|
</div>
|
|
</template>
|
|
<n-button v-else>
|
|
<template #icon><n-icon :component="CloudUploadOutline" /></template>
|
|
{{ t('common.action.upload') }}
|
|
</n-button>
|
|
</n-upload>
|
|
</template>
|
|
|
|
<script setup lang="ts">
|
|
import { computed } from 'vue';
|
|
import { useI18n } from 'vue-i18n';
|
|
import type { UploadCustomRequestOptions, UploadFileInfo } from 'naive-ui';
|
|
import { AddOutline, CloudUploadOutline } from '@vicons/ionicons5';
|
|
import { post } from '@/api/request';
|
|
import { message } from '@/utils/feedback';
|
|
|
|
interface MediaItem {
|
|
key: string;
|
|
url?: string;
|
|
name?: string;
|
|
type?: string;
|
|
}
|
|
|
|
const props = withDefaults(
|
|
defineProps<{ modelValue: MediaItem[]; type?: 'image' | 'video' | 'file'; max?: number }>(),
|
|
{ type: 'image', max: 8 },
|
|
);
|
|
const emit = defineEmits<{ (e: 'update:modelValue', v: MediaItem[]): void }>();
|
|
const { t } = useI18n();
|
|
|
|
const listType = computed(() => (props.type === 'image' ? 'image-card' : 'text'));
|
|
const accept = computed(() =>
|
|
props.type === 'image' ? 'image/*' : props.type === 'video' ? 'video/*' : 'application/pdf,image/*',
|
|
);
|
|
|
|
const fileList = computed<UploadFileInfo[]>(() =>
|
|
(props.modelValue || []).map((m) => ({
|
|
id: m.key,
|
|
name: m.name || m.key,
|
|
status: 'finished',
|
|
url: m.url,
|
|
})),
|
|
);
|
|
|
|
async function doUpload({ file, onFinish, onError }: UploadCustomRequestOptions) {
|
|
try {
|
|
const fd = new FormData();
|
|
fd.append('file', file.file as File);
|
|
const res: any = await post(`/upload?type=${props.type}`, fd);
|
|
emit('update:modelValue', [
|
|
...(props.modelValue || []),
|
|
{ key: res.key, url: res.url, name: res.name, type: props.type },
|
|
]);
|
|
onFinish();
|
|
} catch (e) {
|
|
message.error((e as Error)?.message || 'upload failed');
|
|
onError();
|
|
}
|
|
}
|
|
|
|
function onRemove({ file }: { file: UploadFileInfo }) {
|
|
emit('update:modelValue', (props.modelValue || []).filter((m) => m.key !== file.id));
|
|
return true;
|
|
}
|
|
</script>
|
|
|
|
<style scoped>
|
|
.upd-trigger {
|
|
display: flex;
|
|
flex-direction: column;
|
|
align-items: center;
|
|
justify-content: center;
|
|
gap: 4px;
|
|
font-size: 12px;
|
|
color: #6b7280;
|
|
}
|
|
</style>
|