TransferImageUpload.vue 11 KB
<template>
    <div class="transfer-image-upload">
        <!-- 隐藏的input -->
        <input
            ref="fileInputRef"
            type="file"
            accept="image/jpeg,image/jpg,image/png,image/jpeg"
            :multiple="!slotMode"
            class="hidden-input"
            @change="onFileChange"
        />

        <!-- 槽位模式:每个槽位独立上传一张,按钮文案为「上传+标题」 -->
        <div v-if="slotMode" class="slot-list">
            <div
                v-for="(title, slotIndex) in slotTitles"
                :key="slotIndex"
                class="slot-item"
            >
                <div v-if="slottedImages[slotIndex]" class="upload-item slot-upload-item">
                    <a-image :src="slottedImages[slotIndex]" class="image-preview" />
                    <div class="delete-icon" @click="handleSlotDelete(slotIndex)">
                        <CloseCircleOutlined />
                    </div>
                </div>
                <div
                    v-else-if="!readonly"
                    class="upload-btn slot-upload-btn"
                    @click="handleSlotUploadClick(slotIndex)"
                >
                    <PlusOutlined class="plus-icon" />
                    <div class="upload-text">{{ title ? `上传${title}` : (uploadText || '上传图片') }}</div>
                </div>
                <div v-else class="upload-placeholder">
                    暂无图片
                </div>
            </div>
        </div>

        <!-- 普通模式:保持原有样式 -->
        <div v-else class="upload-list">
            <div
                v-for="(url, index) in imageList"
                :key="index"
                class="upload-item"
            >
                <a-image :src="url" class="image-preview" />
                <div class="delete-icon" @click="handleDelete(index)">
                    <CloseCircleOutlined />
                </div>
            </div>

            <div
                v-if="imageList.length < maxCount && !readonly"
                class="upload-btn"
                @click="handleUploadClick"
            >
                <PlusOutlined class="plus-icon" />
                <div class="upload-text">{{ uploadText || '上传图片' }}</div>
            </div>
        </div>

        <div v-if="hint" class="upload-hint">{{ hint }}</div>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-facing-decorator";
import { PlusOutlined, CloseCircleOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { uploadFile, isLikelyImageFile } from "@/utils/upload.js";

@Component({
    name: "TransferImageUpload",
    components: { PlusOutlined, CloseCircleOutlined }
})
export default class TransferImageUpload extends Vue {
    @Prop({ type: Array, default: () => [] })
    value!: any[];

    @Prop({ type: Number, default: 10 })
    maxCount!: number;

    @Prop({ type: Number, default: 10 })
    maxSize!: number;

    @Prop({ type: String, default: "" })
    uploadText!: string;

    @Prop({ type: String, default: "" })
    hint!: string;

    @Prop({ type: Boolean, default: false })
    readonly!: boolean;

    @Prop({ type: String, default: "auction/transfer" })
    directory!: string;

    @Prop({ type: Boolean, default: false })
    slotMode!: boolean;

    @Prop({ type: Array, default: () => [] })
    slotTitles!: string[];

    imageList: string[] = [];
    slottedImages: (string | null)[] = [];
    uploading = false;
    currentSlotIndex: number = -1;

    @Watch("slotTitles", { immediate: true })
    onSlotTitlesChange(titles: string[]) {
        if (!this.slotMode) return;
        const len = (titles || []).length;
        const next: (string | null)[] = new Array(len).fill(null);
        for (let i = 0; i < Math.min(len, this.slottedImages.length); i++) {
            next[i] = this.slottedImages[i] || null;
        }
        this.slottedImages = next;
    }

    @Watch("value", { deep: true, immediate: true })
    onValueChange(val: any[]) {
        const urls: string[] = (!val || val.length === 0)
            ? []
            : val.map((item: any) => {
                if (typeof item === "string") return item;
                return item.url || item.aliyunAddress || "";
            }).filter(Boolean);

        if (this.slotMode) {
            const len = (this.slotTitles || []).length || urls.length;
            const next: (string | null)[] = new Array(Math.max(len, urls.length)).fill(null);
            urls.forEach((u, i) => { next[i] = u; });
            this.slottedImages = next;
            this.imageList = this.slottedImages.filter((x): x is string => !!x);
        } else {
            this.imageList = urls;
        }
    }

    handleUploadClick() {
        if (this.readonly || this.uploading) return;
        (this.$refs.fileInputRef as HTMLInputElement)?.click();
    }

    handleSlotUploadClick(slotIndex: number) {
        if (this.readonly || this.uploading) return;
        this.currentSlotIndex = slotIndex;
        (this.$refs.fileInputRef as HTMLInputElement)?.click();
    }

    async onFileChange(ev: Event) {
        const input = ev.target as HTMLInputElement;
        const files = Array.from(input.files || []);
        input.value = "";

        if (files.length === 0) return;

        if (this.slotMode) {
            await this.handleSlotFile(files[0]);
            this.currentSlotIndex = -1;
            return;
        }

        if (this.imageList.length + files.length > this.maxCount) {
            message.warning(`最多上传${this.maxCount}张图片`);
            return;
        }

        for (const file of files) {
            if (!isLikelyImageFile(file)) {
                message.error(`${file.name} 不是有效的图片文件`);
                return;
            }
            if (file.size > this.maxSize * 1024 * 1024) {
                message.error(`${file.name} 大小超过${this.maxSize}MB`);
                return;
            }
        }

        try {
            this.uploading = true;
            const uploadPromises = files.map(file => uploadFile(file, { dir: this.directory }));
            const results = await Promise.all(uploadPromises);
            const newUrls = results.map(res => res.aliyunAddress || res.url || "").filter(Boolean);
            this.imageList = [...this.imageList, ...newUrls];
            this.emitChange();
            message.success("上传成功");
        } catch (error: any) {
            message.error(`上传失败:${error.message || error}`);
        } finally {
            this.uploading = false;
        }
    }

    async handleSlotFile(file: File) {
        if (!file) return;
        const slotIndex = this.currentSlotIndex;
        if (slotIndex < 0) return;

        if (!isLikelyImageFile(file)) {
            message.error(`${file.name} 不是有效的图片文件`);
            return;
        }
        if (file.size > this.maxSize * 1024 * 1024) {
            message.error(`${file.name} 大小超过${this.maxSize}MB`);
            return;
        }

        try {
            this.uploading = true;
            const res = await uploadFile(file, { dir: this.directory });
            const url = res.aliyunAddress || res.url || "";
            if (!url) throw new Error("上传返回地址为空");
            const next = [...this.slottedImages];
            next[slotIndex] = url;
            this.slottedImages = next;
            this.imageList = next.filter((x): x is string => !!x);
            this.emitChange();
            message.success("上传成功");
        } catch (error: any) {
            message.error(`上传失败:${error.message || error}`);
        } finally {
            this.uploading = false;
        }
    }

    handleDelete(index: number) {
        if (this.readonly) return;
        this.imageList.splice(index, 1);
        this.emitChange();
    }

    handleSlotDelete(slotIndex: number) {
        if (this.readonly) return;
        const next = [...this.slottedImages];
        next[slotIndex] = null;
        this.slottedImages = next;
        this.imageList = next.filter((x): x is string => !!x);
        this.emitChange();
    }

    emitChange() {
        const urls = this.slotMode
            ? this.slottedImages.filter((x): x is string => !!x)
            : this.imageList;
        const fileList = urls.map(url => ({
            url,
            uid: `${Date.now()}_${Math.random()}`,
            name: url.split("/").pop() || "",
            status: "done"
        }));
        this.$emit("update:value", fileList);
        this.$emit("change", fileList);
    }
}
</script>

<style scoped lang="less">
.transfer-image-upload {
    width: 100%;

    .hidden-input {
        position: absolute;
        width: 0;
        height: 0;
        pointer-events: none;
        opacity: 0;
    }

    .upload-list {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
    }

    .slot-list {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
    }

    .slot-item {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;

        .slot-label {
            font-size: 13px;
            color: #333;
            font-weight: 500;
            line-height: 1;
        }
    }

    .slot-upload-item,
    .slot-upload-btn,
    .upload-placeholder {
        width: 120px;
        height: 120px;
    }

    .upload-placeholder {
        display: flex;
        align-items: center;
        justify-content: center;
        color: #bfbfbf;
        font-size: 12px;
        border: 1px dashed #e1e3e6;
        border-radius: 6px;
        background: #fafafa;
    }

    .upload-item {
        position: relative;
        width: 88px;
        height: 88px;
        border: 1px solid #e1e3e6;
        border-radius: 6px;
        overflow: hidden;
        background: #f5f7fa;

        .image-preview {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .delete-icon {
            position: absolute;
            top: 2px;
            right: 2px;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 50%;
            cursor: pointer;
            z-index: 10;

            &:hover {
                color: #ff4d4f;
            }
        }
    }

    .upload-btn {
        width: 88px;
        height: 88px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        background: #fafafa;
        transition: all 0.3s;

        &:hover {
            border-color: #1890ff;
        }

        .plus-icon {
            font-size: 20px;
            color: #8c8c8c;
            margin-bottom: 4px;
        }

        .upload-text {
            font-size: 12px;
            color: #8c8c8c;
        }
    }

    .upload-hint {
        color: #999;
        font-size: 12px;
        margin-top: 8px;
    }
}
</style>