Files
guoju0808/ry-vue3/src/components/OssFileUploader.vue
T
2026-08-16 21:24:53 +08:00

152 lines
4.9 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 }" @click="handleClick">
<div v-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" 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="modelValue" target="_blank" @click.stop>{{ fileName }}</a>
<span class="file-type">{{ ext.toUpperCase() }} · {{ fileSizeText }}</span>
</div>
<el-button v-if="!readonly" link type="danger" size="small" class="remove-btn" @click.stop="onRemove">移除</el-button>
</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 { uploadToOss } from '@/utils/oss'
const props = defineProps({
modelValue: { type: String, default: '' },
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 }
})
const emit = defineEmits(['update:modelValue'])
const fileInput = ref(null)
const uploading = ref(false)
const fileName = computed(() => {
if (!props.modelValue) return ''
// 取 URL 最后一段, 去 query 参数
const url = props.modelValue.split('?')[0]
return url.substring(url.lastIndexOf('/') + 1)
})
const ext = computed(() => {
const n = fileName.value
const i = n.lastIndexOf('.')
return i >= 0 ? n.substring(i + 1) : ''
})
const fileSizeText = computed(() => '已上传')
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
try {
const url = await uploadToOss(file, props.dir)
emit('update:modelValue', url)
ElMessage.success('上传成功')
} catch (err) {
ElMessage.error(err.message || '上传失败')
} finally {
uploading.value = false
}
}
function onRemove() {
emit('update:modelValue', '')
}
</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: #1890ff; }
.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-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: #1890ff; 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: #1890ff; text-decoration: underline; }
.file-type { font-size: 12px; color: #909399; }
.remove-btn { flex-shrink: 0; }
</style>