249 lines
9.0 KiB
Vue
249 lines
9.0 KiB
Vue
<!--
|
|
通用 OSS 文件上传控件 (支持 PDF / 图片 / 自定义 accept)
|
|
与 OssImageUploader 不同: 这里不强制要求图片类型, 显示上传的文件名/图标
|
|
用法:
|
|
<oss-file-uploader
|
|
v-model="form.fileUrl"
|
|
:dir="'ry8080/special-plan/'"
|
|
accept=".pdf,.png,.jpg,.jpeg"
|
|
placeholder="点击上传文件"
|
|
/>
|
|
-->
|
|
<template>
|
|
<div class="ht-file-upload" :class="{ 'has-file': modelValue, 'is-block': block, readonly, uploading }" @click="handleClick">
|
|
<div v-if="uploading" class="ht-file-progress">
|
|
<span class="progress-label">上传中</span>
|
|
<el-progress :percentage="progress" :stroke-width="6" class="progress-bar" />
|
|
</div>
|
|
<div v-else-if="!modelValue && !readonly" class="ht-file-placeholder">
|
|
<span class="placeholder-text">{{ placeholder }}</span>
|
|
<span class="placeholder-hint" v-if="hint">{{ hint }}</span>
|
|
</div>
|
|
<div v-else-if="!modelValue && readonly" class="ht-file-placeholder readonly-empty">
|
|
<span class="placeholder-text">未上传</span>
|
|
</div>
|
|
<div v-else-if="modelValue" class="ht-file-info">
|
|
<el-icon class="file-icon" :size="22"><svg viewBox="0 0 24 24" fill="currentColor">
|
|
<path d="M14 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6zm-1 7V3.5L18.5 9H13z"/>
|
|
</svg></el-icon>
|
|
<div class="file-meta">
|
|
<a class="file-name" :href="openHref" target="_blank" @click.stop>{{ fileName }}</a>
|
|
<span class="file-type">{{ ext.toUpperCase() }} · {{ fileSizeText }}</span>
|
|
</div>
|
|
<el-link :underline="false" v-if="!readonly" type="danger" class="remove-btn" @click.stop="onRemove">移除</el-link>
|
|
<!-- 右侧预览框 (图片用 el-image, 其他用 icon + 点击新窗口打开) -->
|
|
<div v-if="showPreview" class="preview-box">
|
|
<el-image v-if="isImage" :src="modelValue" :preview-src-list="[modelValue]" :initial-index="0" fit="cover" class="preview-img" />
|
|
<a v-else :href="openHref" target="_blank" class="preview-file" @click.stop>
|
|
<el-icon :size="28"><Document /></el-icon>
|
|
<span class="preview-text">{{ getFileType(modelValue) }}</span>
|
|
</a>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<input
|
|
type="file"
|
|
ref="fileInput"
|
|
:accept="accept"
|
|
style="display:none"
|
|
@change="onFileChange"
|
|
/>
|
|
</template>
|
|
|
|
<script setup>
|
|
import { ref, computed } from 'vue'
|
|
import { ElMessage } from 'element-plus'
|
|
import { Document } from '@element-plus/icons-vue'
|
|
import { uploadToOss } from '@/utils/oss'
|
|
|
|
const props = defineProps({
|
|
modelValue: { type: String, default: '' },
|
|
name: { type: String, default: '' }, // 原文件名 (v-model:name 回传, 用于显示而非 OSS key)
|
|
dir: { type: String, default: 'ry8080/file/' },
|
|
placeholder: { type: String, default: '点击上传文件' },
|
|
hint: { type: String, default: '' },
|
|
accept: { type: String, default: '.pdf,.png,.jpg,.jpeg' },
|
|
maxSize: { type: Number, default: 10 }, // MB
|
|
block: { type: Boolean, default: false },
|
|
readonly: { type: Boolean, default: false },
|
|
showPreview: { type: Boolean, default: true } // 右侧预览框 (图片/PDF/其他)
|
|
})
|
|
|
|
const emit = defineEmits(['update:modelValue', 'update:name'])
|
|
|
|
const fileInput = ref(null)
|
|
const uploading = ref(false)
|
|
const progress = ref(0)
|
|
|
|
const fileName = computed(() => {
|
|
// 优先用调用方回传的原文件名 (v-model:name); 没有则从 OSS key 还原原名
|
|
if (props.name) return props.name
|
|
if (!props.modelValue) return ''
|
|
// 取 URL 最后一段, 去 query 参数; 上传时已对路径做了 encodeURIComponent, 这里先还原
|
|
const url = props.modelValue.split('?')[0]
|
|
let last = url.substring(url.lastIndexOf('/') + 1)
|
|
try { last = decodeURIComponent(last) } catch (e) { /* 已解码/旧 key, 原样用 */ }
|
|
// 新 key 格式: 原名_时间戳_随机串.扩展名 → 还原 原名.扩展名; 旧 key (无原名) 原样返回
|
|
const m = last.match(/^(.+)_\d{13}_[a-z0-9]{6}(\.[^.]+)?$/)
|
|
if (m) return m[1] + (m[2] || '')
|
|
return last
|
|
})
|
|
const ext = computed(() => {
|
|
const n = fileName.value
|
|
const i = n.lastIndexOf('.')
|
|
return i >= 0 ? n.substring(i + 1) : ''
|
|
})
|
|
const fileSizeText = computed(() => '已上传')
|
|
|
|
// 图片扩展名 (用于 el-image 预览)
|
|
const isImage = computed(() => {
|
|
if (!props.modelValue) return false
|
|
return ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext.value)
|
|
})
|
|
// PDF: 点击不下载, 走 /common/oss/proxy 后端代理重写 Content-Disposition 为 inline, 新窗口内嵌预览
|
|
const isPdf = computed(() => ext.value.toLowerCase() === 'pdf')
|
|
// OSS 代理预览 (与 Preview.vue / PublicityDetail 同技术): bucket 默认 attachment, 直接打开会强制下载
|
|
function proxyUrl(url) {
|
|
if (!url) return url
|
|
if (url.includes('hwtossbamlorgcn.oss-cn-beijing.aliyuncs.com')) {
|
|
return import.meta.env.VITE_APP_BASE_API + '/common/oss/proxy?url=' + encodeURIComponent(url) + '#toolbar=0&zoom=page-width'
|
|
}
|
|
return url
|
|
}
|
|
// 文件名/预览框点击目标: PDF → 代理预览(新窗口), 其余 → 原 URL (图片 el-image 预览, 其他下载)
|
|
const openHref = computed(() => isPdf.value ? proxyUrl(props.modelValue) : props.modelValue)
|
|
// 文件类型标签 (PDF / DOC / XLS / ZIP 等)
|
|
const typeLabelMap = {
|
|
pdf: 'PDF', doc: 'DOC', docx: 'DOCX',
|
|
xls: 'XLS', xlsx: 'XLSX', ppt: 'PPT', pptx: 'PPTX',
|
|
zip: 'ZIP', rar: 'RAR', '7z': '7Z',
|
|
txt: 'TXT', csv: 'CSV'
|
|
}
|
|
function getFileType(url) {
|
|
if (!url) return 'FILE'
|
|
const e = url.split('?')[0].split('.').pop().toLowerCase()
|
|
return typeLabelMap[e] || (e ? e.toUpperCase() : 'FILE')
|
|
}
|
|
|
|
function handleClick() {
|
|
if (props.readonly || uploading.value) return
|
|
fileInput.value?.click()
|
|
}
|
|
|
|
async function onFileChange(e) {
|
|
const file = e.target.files?.[0]
|
|
e.target.value = ''
|
|
if (!file) return
|
|
// 类型校验 (按 accept 列表)
|
|
const allowed = props.accept.split(',').map(s => s.trim().toLowerCase()).filter(Boolean)
|
|
if (allowed.length) {
|
|
const lower = file.name.toLowerCase()
|
|
const ok = allowed.some(rule => {
|
|
if (rule.startsWith('.')) return lower.endsWith(rule)
|
|
if (rule.endsWith('/*')) return file.type.startsWith(rule.slice(0, -1))
|
|
return file.type === rule
|
|
})
|
|
if (!ok) return ElMessage.warning('文件类型不符, 允许: ' + props.accept)
|
|
}
|
|
if (file.size / 1024 / 1024 > props.maxSize) {
|
|
return ElMessage.warning(`文件大小不能超过 ${props.maxSize}MB`)
|
|
}
|
|
uploading.value = true
|
|
progress.value = 0
|
|
try {
|
|
const url = await uploadToOss(file, props.dir, (p) => { progress.value = p })
|
|
emit('update:modelValue', url)
|
|
emit('update:name', file.name)
|
|
ElMessage.success('上传成功')
|
|
} catch (err) {
|
|
ElMessage.error(err.message || '上传失败')
|
|
} finally {
|
|
uploading.value = false
|
|
}
|
|
}
|
|
|
|
function onRemove() {
|
|
emit('update:modelValue', '')
|
|
emit('update:name', '')
|
|
}
|
|
</script>
|
|
|
|
<style scoped>
|
|
.ht-file-upload {
|
|
display: flex;
|
|
align-items: center;
|
|
gap: 10px;
|
|
border: 1px dashed #d9d9d9;
|
|
border-radius: 4px;
|
|
background: #fafafa;
|
|
cursor: pointer;
|
|
padding: 12px 14px;
|
|
transition: border-color 0.2s;
|
|
min-height: 60px;
|
|
}
|
|
.ht-file-upload:hover { border-color: var(--brand-primary); }
|
|
.ht-file-upload.has-file { border-style: solid; border-color: #52c41a; background: #fff; }
|
|
.ht-file-upload.is-block { width: 100%; }
|
|
.ht-file-upload.readonly { cursor: default; }
|
|
.ht-file-upload.uploading { cursor: default; }
|
|
|
|
/* 上传进度条 */
|
|
.ht-file-progress {
|
|
flex: 1;
|
|
display: flex;
|
|
align-items: center;
|
|
gap: 12px;
|
|
min-width: 0;
|
|
}
|
|
.progress-label { font-size: 13px; color: #606266; white-space: nowrap; flex-shrink: 0; }
|
|
.progress-bar { flex: 1; }
|
|
|
|
.ht-file-placeholder {
|
|
flex: 1;
|
|
display: flex; flex-direction: column;
|
|
align-items: center; justify-content: center;
|
|
gap: 4px;
|
|
}
|
|
.placeholder-text { font-size: 14px; color: #8c8c8c; }
|
|
.placeholder-hint { font-size: 12px; color: #c0c4cc; }
|
|
|
|
.ht-file-info {
|
|
display: flex; align-items: center; gap: 12px; flex: 1; min-width: 0;
|
|
}
|
|
.file-icon { color: var(--brand-primary); flex-shrink: 0; }
|
|
.file-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
|
|
.file-name {
|
|
font-size: 14px; color: #1a1a1a; font-weight: 500;
|
|
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
|
cursor: pointer;
|
|
}
|
|
.file-name:hover { color: var(--brand-primary); text-decoration: underline; }
|
|
.file-type { font-size: 12px; color: #909399; }
|
|
.remove-btn { flex-shrink: 0; }
|
|
|
|
/* 右侧预览框 (方形, 64x64) */
|
|
.preview-box {
|
|
width: 64px;
|
|
height: 64px;
|
|
border: 1px solid #f0f0f0;
|
|
border-radius: 4px;
|
|
background: #fafafa;
|
|
overflow: hidden;
|
|
flex-shrink: 0;
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
}
|
|
.preview-img { width: 100%; height: 100%; cursor: pointer; }
|
|
.preview-file {
|
|
display: flex; flex-direction: column;
|
|
align-items: center; justify-content: center;
|
|
gap: 2px;
|
|
width: 100%; height: 100%;
|
|
color: #8c8c8c;
|
|
text-decoration: none;
|
|
transition: color 0.2s;
|
|
}
|
|
.preview-file:hover { color: var(--brand-primary); }
|
|
.preview-text { font-size: 10px; font-weight: 500; }
|
|
</style> |