Files
api-client/src/components/SingleUpload/index.vue

135 lines
3.2 KiB
Vue
Raw Normal View History

2025-03-28 18:28:06 +08:00
<template>
<div class="single-upload">
<el-upload
:action="uploadUrl"
:before-upload="beforeUpload"
class="uploader"
:file-list="fileList"
:headers="uploadHeaders"
:on-error="handleError"
:on-success="handleSuccess"
:show-file-list="false"
>
<img v-if="fileUrl" alt="avatar" class="avatar" :src="fileUrl" />
<i v-else class="el-icon-plus uploader-icon"></i>
</el-upload>
</div>
</template>
<script>
import { getAccessToken } from '@/utils/accessToken'
export default {
name: 'SingleUpload',
props: {
value: {
type: String,
default: '',
},
uploadUrl: {
type: String,
required: true,
},
2025-04-30 23:34:59 +08:00
picUrl: {
type: String,
default: '',
},
2025-03-28 18:28:06 +08:00
},
data() {
return {
fileUrl: this.value,
fileList: [],
token: getAccessToken() || '',
loadingInstance: null, // 存储 loading 实例
}
},
computed: {
// 设置上传时的 headers
uploadHeaders() {
2025-05-09 15:41:44 +08:00
let userId = ''
let appId = ''
if (this.$store.state?.user?.userId) {
userId = this.$store.state?.user?.userId
}
if (this.$store.state?.user?.appId) {
appId = this.$store.state?.user?.appId
}
2025-03-28 18:28:06 +08:00
return {
Authorization: `${this.token}`,
2025-05-09 15:41:44 +08:00
'x-user-id': userId,
'x-app-id': appId,
2025-03-28 18:28:06 +08:00
}
},
},
watch: {
value: {
handler(val) {
this.fileUrl = val
},
immediate: true,
},
},
methods: {
isImage() {
return /\.(png|jpg|jpeg|gif|webp)$/i.test(this.fileUrl)
},
handleSuccess(response) {
if (response.code === 200) {
this.fileUrl = `https://file.lihailezzc.com/${response.data.key}`
this.$message.success('上传成功!')
2026-01-19 18:05:36 +08:00
this.$emit('input', this.fileUrl)
2025-03-28 18:28:06 +08:00
this.$emit('upload-success', this.fileUrl)
} else {
this.$message.error('上传失败,请重试!')
}
this.loadingInstance.close()
},
handleError() {
this.$message.error('上传失败,请重试!')
this.loadingInstance.close()
},
beforeUpload(file) {
const isValidSize = file.size / 1024 / 1024 < 5
if (!isValidSize) {
this.$message.error('文件大小不能超过 5MB')
return false
}
this.loadingInstance = this.$loading({
target: this.$el, // 加载指示器的父容器
text: '上传中...',
spinner: true, // 显示加载动画
background: 'rgba(0, 0, 0, 0.5)', // 背景遮罩
})
return true
},
},
}
</script>
<style lang="scss" scoped>
.single-upload {
.uploader {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
&:hover {
border-color: #409eff;
}
}
.uploader-icon {
font-size: 28px;
color: #8c939d;
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
}
.avatar {
width: 100px;
height: 100px;
display: block;
}
}
</style>