customizeUploadFile.vue 8.46 KB
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";

import { uploadFile } from "@/utils/upload.js";
import { showToast } from "vant";

const props = defineProps({
	item: {
		type: Object,
		default: () => {},
	},
});

const emit = defineEmits(["update"]);

const uploading = ref(false);

const pickerValue = ref([]);
const fileInputRef = ref<HTMLInputElement | null>(null);

function pickFile() {
	fileInputRef.value?.click();
}

// 页面加载时初始化数据
onMounted(() => {
	initData();
});

// 初始化数据
function initData() {
	pickerValue.value = [];
	if (props?.item?.inspectionResultVO) {
		const inspectionValueList = props?.item?.inspectionResultVO?.inspectionValueList || [];
		for (const i of inspectionValueList) {
			if (i.valueText) { pickerValue.value.push(i.valueText); }
		}
	}
	updateData();
}

// 计算属性
const validationRules = computed(() => {
	return JSON.parse(props.item.validationRules || "{}");
});

async function onFileChange(ev: Event) {
	const input = ev.target as HTMLInputElement;
	const file = input.files?.[0];
	input.value = "";
	if (!file) return;
	const maxSize10MB = 10 * 1024 * 1024;
	const maxSize100MB = 100 * 1024 * 1024;	
	if (props.item.interactionType == "image_upload" && file.size > maxSize10MB) {
		showToast("文件大小不能超过10MB");
		return;
	}
	if (props.item.interactionType == "video_upload" && file.size > maxSize100MB) {
		showToast("文件大小不能超过100MB");
		return;
	}
	uploading.value = true;
	try {
		const res = await uploadFile(file);
		const url = (typeof res.aliyunAddress === "string" && res.aliyunAddress) || (typeof res.url === "string" && res.url) || "";
		showToast("上传成功");
		pickerValue.value.push(url);
		console.log("pickerValue.value", pickerValue.value);
	    sourceSrcUrl.value = "";
	    sourceUrl.value = [];
	    videoShow.value = false;
		updateData();
	} catch (error: unknown) {
		const msg = error instanceof Error ? error.message : String(error);
		showToast(`上传失败:${msg}`);
	} finally {
		uploading.value = false;
	}
}

function handleDelete(item: string) {
	pickerValue.value = pickerValue.value.filter((i) => i !== item);
	console.log("pickerValue.value111111111111111", pickerValue.value);
	// 清除视频预览状态,防止缓存
	sourceSrcUrl.value = "";
	sourceUrl.value = [];
	videoShow.value = false;
	updateData();
}

function updateData() {
	if (pickerValue.value.length > 0) {
		emit("update", JSON.stringify(pickerValue.value));
	} else {
		emit("update", "");
	}
}

// 图片预览
const imagePreview = ref(false);
const previewImagesList = ref([]);
function previewImage(url: string) {
	previewImagesList.value = [url];
	imagePreview.value = true;
}


// 视频预览
const videoShow = ref(false);
const sourceUrl = ref([]);
const sourceSrcUrl = ref("");


function previewVideo(url: string) {
	// 添加时间戳参数,防止浏览器缓存
	const timestamp = new Date().getTime();
	const urlWithTimestamp = url.includes('?') ? `${url}&t=${timestamp}` : `${url}?t=${timestamp}`;
	sourceSrcUrl.value = urlWithTimestamp;
	sourceUrl.value = [urlWithTimestamp];
	console.log("sourceUrl.value", sourceUrl.value);
	videoShow.value = true;
}

</script>

<template>
    <div>
        <van-overlay :show="uploading"
                     teleport="#vant-portal-host"
                     z-index="2000">
            <div class="loadingBox">
                <van-loading color="#1989fa"
                             size="24px"
                             vertical>
                    上传中...
                </van-loading>
            </div>
        </van-overlay>

        <!-- 图片预览 -->
        <van-image-preview v-model:show="imagePreview" :closeable="true" :close-on-click-image="false" :images="previewImagesList"></van-image-preview>

        <!-- 视频预览 -->
        <van-image-preview v-model:show="videoShow"
                           :close-on-click-image="false"
                           :closeable="true"
                           :images="sourceUrl">
            <template #image="{ src }">
                <video controls style="width: 100%;">
                    <source :src="sourceSrcUrl" />
                </video>
            </template>
        </van-image-preview>

        <div class="buttonSelect">
            <div class="title">
                <div class="titleContent">
                    <span v-if="item.required === 1" class="isRequired">*</span>
                    <span>{{ item.nodeName }}</span>
                </div>
                <div v-if="validationRules.maxCount && validationRules.maxCount.length > 1 && item.interactionType == 'image_upload'"
                     class="titleTip">
                    有损伤请拍摄图片,无损伤请忽略
                </div>
            </div>
            <input ref="fileInputRef"
                   :accept="item.interactionType == 'image_upload' ? 'image/*' : 'video/*'"
                   class="hidden-input"
                   type="file"
                   @change="onFileChange">
            <div class="uploadPage">
                <div v-if="(validationRules.maxCount || 3) > pickerValue.length"
                     class="uploadBox"
                     @click="pickFile">
                    <van-icon class="plusBox"
                              color="#999999"
                              name="plus"
                              size="24" />
                    <div class="uploadTxt">
                        {{ item.interactionType == 'image_upload' ? '添加照片' : '添加视频' }}
                    </div>
                </div>
                <div v-for="(url, index) in pickerValue"
                     :key="index"
                     class="uploadBox">
                    <!-- 删除按钮 -->
                    <div class="deleteBox" @click="handleDelete(url)">
                        <van-icon color="#999999"
                                  name="clear"
                                  size="20" />
                    </div>
                    <!-- 图片 -->
                    <van-image v-if="item.interactionType == 'image_upload'"
                               class="uploadBoxImg"
                               radius="8px"
                               :src="url"
                               @click="previewImage(url)" />
                    <!-- 视频 -->
                    <video v-if="item.interactionType == 'video_upload'"
                           class="uploadBoxImg"
                           controls
                           :src="url">
                        您的浏览器不支持 video 标签。
                    </video>
                    <!-- 点击视频预览 -->
                    <div v-if="item.interactionType == 'video_upload'"
                         class="videoPreviewBox"
                         @click="previewVideo(url)">
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.buttonSelect {
	float: left;
	width: 100%;
	background: #fff;
}

.title {
	float: left;
	width: 100%;
	padding-left: 16px;
	margin-top: 16px;
	margin-bottom: 10px;
}

.titleContent {
	float: left;
	width: 100%;
	height: 24px;
	font-size: 14px;
	line-height: 24px;
	color: #141e34;
}

.titleTip {
	float: left;
	width: 100%;
	height: 16px;
	font-size: 12px;
	font-weight: 400;
	line-height: 16px;
	color: #999;
}

.isRequired {
	padding-right: 2px;
	font-size: 14px;
	color: #ee3040;
}

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

.uploadPage {
	float: left;
	width: calc(100% - 24px);
	margin-left: 12px;
}

.uploadBox {
	position: relative;
	float: left;
	width: 96px;
	height: 96px;
	margin-right: 12px;
	margin-bottom: 16px;
	background: #f9f9f9;
	border: 1px solid #f9f9f9;
	border-radius: 8px;
}

.uploadBoxImg {
    width: 100%;
    height: 100%;
    z-index: 9;
	border-radius: 8px;
}

.plusBox {
	float: left;
	margin-top: 22px;
	margin-right: 36px;
	margin-left: 36px;
}

.uploadTxt {
	float: left;
	width: 100%;
	height: 20px;
	margin-top: 8px;
	font-size: 12px;
	font-weight: 400;
	line-height: 20px;
	color: #999;
	text-align: center;
}

.deleteBox {
	position: absolute;
	top: 2px;
	right: 2px;
	z-index: 999;
	width: 20px;
	height: 20px;
	cursor: pointer;
}

.loadingBox {
	position: absolute;
	top: 50%;
	left: 50%;
	width: 80px;
	height: 80px;
	transform: translate(-50%, -50%);
}

.videoPreviewBox {
	position: absolute;
	top: 0px;
	left: 0;
	width: 96px;
	height: 96px;
	background: rgba(0, 0, 0, 0.5);
	opacity: 0.1;
	z-index: 9;
}
</style>