|
@@ -1,18 +1,18 @@
|
|
|
<template>
|
|
|
<div class="upload-box">
|
|
|
<el-upload
|
|
|
- v-model:file-list="_fileList"
|
|
|
- action="#"
|
|
|
+ :file-list="_fileList"
|
|
|
+ :action="uploadImgUrl"
|
|
|
list-type="picture-card"
|
|
|
- :class="['upload', self_disabled ? 'disabled' : '', drag ? 'no-border' : '']"
|
|
|
- :multiple="true"
|
|
|
- :disabled="self_disabled"
|
|
|
- :limit="limit"
|
|
|
- :http-request="handleHttpUpload"
|
|
|
:before-upload="beforeUpload"
|
|
|
- :on-exceed="handleExceed"
|
|
|
:on-success="uploadSuccess"
|
|
|
+ :on-exceed="handleExceed"
|
|
|
:on-error="uploadError"
|
|
|
+ :class="['upload', self_disabled ? 'disabled' : '', drag ? 'no-border' : '', { hide: _fileList.length >= limit }]"
|
|
|
+ :multiple="true"
|
|
|
+ :headers="headers"
|
|
|
+ :disabled="self_disabled"
|
|
|
+ :limit="limit"
|
|
|
:drag="drag"
|
|
|
:accept="fileType.join(',')"
|
|
|
>
|
|
@@ -36,6 +36,16 @@
|
|
|
</div>
|
|
|
</template>
|
|
|
</el-upload>
|
|
|
+ <div v-if="showTip" class="el-upload__tip">
|
|
|
+ 请上传
|
|
|
+ <template v-if="fileSize">
|
|
|
+ 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
|
|
|
+ </template>
|
|
|
+ <template v-if="fileType">
|
|
|
+ 格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
|
|
|
+ </template>
|
|
|
+ 的文件
|
|
|
+ </div>
|
|
|
<div class="el-upload__tip">
|
|
|
<slot name="tip"></slot>
|
|
|
</div>
|
|
@@ -46,13 +56,17 @@
|
|
|
<script setup lang="ts" name="UploadImgs">
|
|
|
import { ref, computed, inject, watch } from 'vue'
|
|
|
import { Plus } from '@element-plus/icons-vue'
|
|
|
-import { uploadImg } from '@/api/modules/upload'
|
|
|
-import type { UploadProps, UploadFile, UploadUserFile, UploadRequestOptions } from 'element-plus'
|
|
|
-import { ElNotification, formContextKey, formItemContextKey } from 'element-plus'
|
|
|
-
|
|
|
+import type { UploadProps, UploadFile } from 'element-plus'
|
|
|
+import { ElMessage, formContextKey, formItemContextKey } from 'element-plus'
|
|
|
+import { listToString } from '@/utils/common'
|
|
|
+import { showFullScreenLoading, tryHideFullScreenLoading } from '@/components/Loading/fullScreen'
|
|
|
+import { compressAccurately } from 'image-conversion'
|
|
|
+import { OssVO } from '@/api/interface/system/oss'
|
|
|
+import { globalHeaders } from '@/api'
|
|
|
+import { getListByIdsApi, delOssApi } from '@/api/modules/system/oss'
|
|
|
+import { ResultData } from '@/api/interface'
|
|
|
interface UploadFileProps {
|
|
|
- fileList: UploadUserFile[]
|
|
|
- api?: (params: any) => Promise<any> // 上传图片的 api 方法,一般项目上传都是同一个 api 方法,在组件里直接引入即可 ==> 非必传
|
|
|
+ modelValue: string | object | Array<any>
|
|
|
drag?: boolean // 是否支持拖拽上传 ==> 非必传(默认为 true)
|
|
|
disabled?: boolean // 是否禁用上传组件 ==> 非必传(默认为 false)
|
|
|
limit?: number // 最大图片上传数 ==> 非必传(默认为 5张)
|
|
@@ -60,21 +74,30 @@ interface UploadFileProps {
|
|
|
fileType?: File.ImageMimeType[] // 图片类型限制 ==> 非必传(默认为 ["image/jpeg", "image/png", "image/gif"])
|
|
|
height?: string // 组件高度 ==> 非必传(默认为 150px)
|
|
|
width?: string // 组件宽度 ==> 非必传(默认为 150px)
|
|
|
+ isShowTip?: boolean
|
|
|
borderRadius?: string // 组件边框圆角 ==> 非必传(默认为 8px)
|
|
|
+ compressSupport?: boolean // 是否支持图片压缩 ==> 非必传(默认为 false)
|
|
|
+ compressTargetSize?: number // 图片压缩目标大小 ==> 非必传(默认为 300kb)
|
|
|
}
|
|
|
|
|
|
const props = withDefaults(defineProps<UploadFileProps>(), {
|
|
|
- fileList: () => [],
|
|
|
+ modelValue: () => '',
|
|
|
drag: true,
|
|
|
disabled: false,
|
|
|
limit: 5,
|
|
|
fileSize: 5,
|
|
|
+ isShowTip: true,
|
|
|
+ compressSupport: false,
|
|
|
+ compressTargetSize: 300,
|
|
|
fileType: () => ['image/jpeg', 'image/png', 'image/gif'],
|
|
|
height: '150px',
|
|
|
width: '150px',
|
|
|
borderRadius: '8px'
|
|
|
})
|
|
|
|
|
|
+const baseUrl = import.meta.env.VITE_API_URL
|
|
|
+const uploadImgUrl = ref(baseUrl + '/common/upload') // 上传的图片服务器地址
|
|
|
+const headers = ref(globalHeaders())
|
|
|
// 获取 el-form 组件上下文
|
|
|
const formContext = inject(formContextKey, void 0)
|
|
|
// 获取 el-form-item 组件上下文
|
|
@@ -83,15 +106,42 @@ const formItemContext = inject(formItemContextKey, void 0)
|
|
|
const self_disabled = computed(() => {
|
|
|
return props.disabled || formContext?.disabled
|
|
|
})
|
|
|
-
|
|
|
-const _fileList = ref<UploadUserFile[]>(props.fileList)
|
|
|
-
|
|
|
-// 监听 props.fileList 列表默认值改变
|
|
|
+const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize))
|
|
|
+const _fileList = ref<any[]>([])
|
|
|
+const uploadList = ref<any[]>([])
|
|
|
+const number = ref(0)
|
|
|
+const imageUploadRef = ref<ElUploadInstance>()
|
|
|
+// 监听 props.modelValue 列表默认值改变
|
|
|
watch(
|
|
|
- () => props.fileList,
|
|
|
- (n: UploadUserFile[]) => {
|
|
|
- _fileList.value = n
|
|
|
- }
|
|
|
+ () => props.modelValue,
|
|
|
+ async (val: string | object | Array<any>) => {
|
|
|
+ if (val) {
|
|
|
+ // 首先将值转为数组
|
|
|
+ let list: OssVO[] = []
|
|
|
+ if (Array.isArray(val)) {
|
|
|
+ list = val as OssVO[]
|
|
|
+ } else {
|
|
|
+ const res = await getListByIdsApi(val)
|
|
|
+ list = res.data
|
|
|
+ }
|
|
|
+ // 然后将数组转为对象数组
|
|
|
+ _fileList.value = list.map(item => {
|
|
|
+ // 字符串回显处理 如果此处存的是url可直接回显 如果存的是id需要调用接口查出来
|
|
|
+ let itemData
|
|
|
+ if (typeof item === 'string') {
|
|
|
+ itemData = { name: item, url: item }
|
|
|
+ } else {
|
|
|
+ // 此处name使用ossId 防止删除出现重名
|
|
|
+ itemData = { name: item.ossId, url: item.url, ossId: item.ossId }
|
|
|
+ }
|
|
|
+ return itemData
|
|
|
+ })
|
|
|
+ } else {
|
|
|
+ _fileList.value = []
|
|
|
+ return []
|
|
|
+ }
|
|
|
+ },
|
|
|
+ { deep: true, immediate: true }
|
|
|
)
|
|
|
|
|
|
/**
|
|
@@ -101,37 +151,21 @@ watch(
|
|
|
const beforeUpload: UploadProps['beforeUpload'] = rawFile => {
|
|
|
const imgSize = rawFile.size / 1024 / 1024 < props.fileSize
|
|
|
const imgType = props.fileType.includes(rawFile.type as File.ImageMimeType)
|
|
|
- if (!imgType)
|
|
|
- ElNotification({
|
|
|
- title: '温馨提示',
|
|
|
- message: '上传图片不符合所需的格式!',
|
|
|
- type: 'warning'
|
|
|
- })
|
|
|
- if (!imgSize)
|
|
|
- setTimeout(() => {
|
|
|
- ElNotification({
|
|
|
- title: '温馨提示',
|
|
|
- message: `上传图片大小不能超过 ${props.fileSize}M!`,
|
|
|
- type: 'warning'
|
|
|
- })
|
|
|
- }, 0)
|
|
|
- return imgType && imgSize
|
|
|
-}
|
|
|
-
|
|
|
-/**
|
|
|
- * @description 图片上传
|
|
|
- * @param options upload 所有配置项
|
|
|
- * */
|
|
|
-const handleHttpUpload = async (options: UploadRequestOptions) => {
|
|
|
- let formData = new FormData()
|
|
|
- formData.append('file', options.file)
|
|
|
- try {
|
|
|
- const api = props.api ?? uploadImg
|
|
|
- const { data } = await api(formData)
|
|
|
- options.onSuccess(data)
|
|
|
- } catch (error) {
|
|
|
- options.onError(error as any)
|
|
|
+ if (!imgType) {
|
|
|
+ ElMessage.error(`上传图片不符合所需的格式, 请上传${props.fileType.join('/')}图片格式文件!`)
|
|
|
+ return false
|
|
|
}
|
|
|
+ if (!imgSize) {
|
|
|
+ ElMessage.error('图片大小不能超过 ' + props.fileSize + 'M!')
|
|
|
+ return false
|
|
|
+ }
|
|
|
+ if (props.compressSupport && rawFile.size / 1024 > props.compressTargetSize) {
|
|
|
+ return compressAccurately(rawFile, props.compressTargetSize)
|
|
|
+ }
|
|
|
+ showFullScreenLoading('正在上传图片,请稍候...')
|
|
|
+ number.value++
|
|
|
+ console.log('number', number.value)
|
|
|
+ return imgType && imgSize
|
|
|
}
|
|
|
|
|
|
/**
|
|
@@ -140,19 +174,31 @@ const handleHttpUpload = async (options: UploadRequestOptions) => {
|
|
|
* @param uploadFile 上传的文件
|
|
|
* */
|
|
|
const emit = defineEmits<{
|
|
|
- 'update:fileList': [value: UploadUserFile[]]
|
|
|
+ 'update:modelValue': [value: string]
|
|
|
}>()
|
|
|
-const uploadSuccess = (response: { fileUrl: string } | undefined, uploadFile: UploadFile) => {
|
|
|
- if (!response) return
|
|
|
- uploadFile.url = response.fileUrl
|
|
|
- emit('update:fileList', _fileList.value)
|
|
|
- // 调用 el-form 内部的校验方法(可自动校验)
|
|
|
+const uploadSuccess = (response: ResultData, uploadFile: UploadFile) => {
|
|
|
+ if (response.code !== 200) {
|
|
|
+ number.value--
|
|
|
+ ElMessage.error(response.msg)
|
|
|
+ imageUploadRef.value?.handleRemove(uploadFile)
|
|
|
+ uploadedSuccessfully()
|
|
|
+ return
|
|
|
+ }
|
|
|
+ uploadList.value.push({ name: response.data.fileName, url: response.data.url, ossId: response.data.ossId })
|
|
|
+ uploadedSuccessfully()
|
|
|
+}
|
|
|
+
|
|
|
+// 上传结束处理
|
|
|
+const uploadedSuccessfully = () => {
|
|
|
+ if (number.value > 0 && uploadList.value.length === number.value) {
|
|
|
+ _fileList.value = _fileList.value.filter(f => f.url !== undefined).concat(uploadList.value)
|
|
|
+ uploadList.value = []
|
|
|
+ number.value = 0
|
|
|
+ emit('update:modelValue', listToString(_fileList.value))
|
|
|
+ tryHideFullScreenLoading()
|
|
|
+ }
|
|
|
+ // 监听表单验证
|
|
|
formItemContext?.prop && formContext?.validateField([formItemContext.prop as string])
|
|
|
- ElNotification({
|
|
|
- title: '温馨提示',
|
|
|
- message: '图片上传成功!',
|
|
|
- type: 'success'
|
|
|
- })
|
|
|
}
|
|
|
|
|
|
/**
|
|
@@ -160,30 +206,30 @@ const uploadSuccess = (response: { fileUrl: string } | undefined, uploadFile: Up
|
|
|
* @param file 删除的文件
|
|
|
* */
|
|
|
const handleRemove = (file: UploadFile) => {
|
|
|
- _fileList.value = _fileList.value.filter(item => item.url !== file.url || item.name !== file.name)
|
|
|
- emit('update:fileList', _fileList.value)
|
|
|
+ const fIndex = _fileList.value.map(f => f.name).indexOf(file.name)
|
|
|
+ if (fIndex > -1 && uploadList.value.length === number.value) {
|
|
|
+ let ossId = _fileList.value[fIndex].ossId
|
|
|
+ delOssApi(ossId)
|
|
|
+ _fileList.value.splice(fIndex, 1)
|
|
|
+ emit('update:modelValue', listToString(_fileList.value))
|
|
|
+ formItemContext?.prop && formContext?.validateField([formItemContext.prop as string])
|
|
|
+ return false
|
|
|
+ }
|
|
|
+ return true
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* @description 图片上传错误
|
|
|
* */
|
|
|
const uploadError = () => {
|
|
|
- ElNotification({
|
|
|
- title: '温馨提示',
|
|
|
- message: '图片上传失败,请您重新上传!',
|
|
|
- type: 'error'
|
|
|
- })
|
|
|
+ ElMessage.error('图片上传失败,请您重新上传!')
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* @description 文件数超出
|
|
|
* */
|
|
|
const handleExceed = () => {
|
|
|
- ElNotification({
|
|
|
- title: '温馨提示',
|
|
|
- message: `当前最多只能上传 ${props.limit} 张图片,请移除后上传!`,
|
|
|
- type: 'warning'
|
|
|
- })
|
|
|
+ ElMessage.warning(`当前最多只能上传 ${props.limit} 张图片,请移除后上传!`)
|
|
|
}
|
|
|
|
|
|
/**
|
|
@@ -310,7 +356,6 @@ const handlePictureCardPreview: UploadProps['onPreview'] = file => {
|
|
|
}
|
|
|
.el-upload__tip {
|
|
|
line-height: 15px;
|
|
|
- text-align: center;
|
|
|
}
|
|
|
}
|
|
|
</style>
|