上传图片组件

This commit is contained in:
陈红丽 2024-07-15 09:20:37 +08:00
parent 1dde2138a7
commit d87ce9a414
3 changed files with 665 additions and 3 deletions

View File

@ -0,0 +1,334 @@
<template>
<div class="upload-box">
<el-upload
action="#"
:id="uuid"
:class="['upload', self_disabled ? 'disabled' : '', drag ? 'no-border' : '']"
:multiple="false"
:disabled="loading?true:self_disabled"
:show-file-list="false"
:http-request="handleHttpUpload"
:before-upload="beforeUpload"
:on-error="uploadError"
:drag="drag"
:accept="fileType.join(',')"
>
<template v-if="imageUrl">
<img v-if="imageUrl.indexOf('.pdf')<0" :src="imageUrl" class="upload-image" />
<div v-else class="upload-image">{{imageUrl}}</div>
<div class="upload-handle" @click.stop>
<div class="handle-icon" @click="editImg" v-if="!self_disabled">
<el-icon :size="props.iconSize">
<Edit />
</el-icon>
</div>
<div class="handle-icon" @click="viewImg">
<el-icon :size="props.iconSize">
<ZoomIn />
</el-icon>
</div>
<div class="handle-icon" @click="deleteImg" v-if="!self_disabled">
<el-icon :size="props.iconSize">
<Delete />
</el-icon>
</div>
</div>
</template>
<template v-else>
<div class="upload-empty">
<slot name="empty">
<el-icon v-if="!loading"><Plus /></el-icon>
<span v-else>上传中{{progress}}%</span>
<!-- <span>请上传图片</span> -->
</slot>
</div>
</template>
</el-upload>
<div class="el-upload__tip">
<slot name="tip"></slot>
</div>
<el-image-viewer
:teleported="true"
v-if="imgViewVisible"
@close="imgViewVisible = false"
:url-list="[imageUrl.includes('http') ? imageUrl : baseURL + imageUrl]"
/>
</div>
</template>
<script setup lang="ts" name="UploadImg">
import { ref, computed, inject } from 'vue';
import { ElNotification, formContextKey, formItemContextKey } from 'element-plus';
import type { UploadProps, UploadRequestOptions } from 'element-plus';
import { generateUUID } from '@/utils/auth';
import {upload} from '@/api/common'
interface UploadFileProps {
imageUrl?: string; // ==>
uploadFileUrl?: string; // api api ==>
drag?: boolean; // ==> true
disabled?: boolean; // ==> false
fileSize?: number; // ==> 5M
fileType?: File.ImageMimeType[]; // ==> ["image/jpeg", "image/png", "image/gif"]
height?: string; // ==> 150px
width?: string; // ==> 150px
borderRadius?: string; // ==> 8px
iconSize?: number;
name?: string;
}
//
const props = withDefaults(defineProps<UploadFileProps>(), {
imageUrl: '',
uploadFileUrl: '/admin/file/upload',
drag: true,
disabled: false,
fileSize: 5,
fileType: () => ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'],
height: '150px',
width: '150px',
borderRadius: '8px',
name:''
});
// id
const uuid = ref('id-' + generateUUID());
const viewImg=()=>{
if(props.imageUrl.indexOf('.pdf')<0){
imgViewVisible.value = true
}else{
window.open(props.imageUrl)
}
}
//
const imgViewVisible = ref(false);
// el-form
const formContext = inject(formContextKey, void 0);
// el-form-item
const formItemContext = inject(formItemContextKey, void 0);
//
const self_disabled = computed(() => {
return props.disabled || formContext?.disabled;
});
/**
* @description 图片上传
* @param options upload 所有配置项
* */
interface UploadEmits {
(e: 'update:imageUrl', value: string): void,
(e: 'changeFileName', value: string): void;
}
const oImg=ref('')
const fileName=ref('')
const emit = defineEmits<UploadEmits>();
const loading=ref(false)
const progress=ref(0)
const actionFile=async (fileChild:any)=>{
loading.value=true
try {
const formData = new FormData()
formData.append('file',fileChild)
formData.append('name',props.name)
const res =await upload(formData)
console.log(res)
emit('update:imageUrl',res.fileUrl);
emit('changeFileName',res.fileName)
// el-form
formItemContext?.prop && formContext?.validateField([formItemContext.prop as string]);
} catch (error) {
emit('update:imageUrl','');
emit('changeFileName','')
}finally {
progress.value=0
loading.value=false
}
}
const handleHttpUploadOptions=ref({})
const handleHttpUpload = async (options: UploadRequestOptions) => {
handleHttpUploadOptions.value=options
actionFile(options.file)
};
/**
* @description 删除图片
* */
const deleteImg = () => {
emit('update:imageUrl', '');
emit('changeFileName','')
};
/**
* @description 编辑图片
* */
const editImg = () => {
const dom = document.querySelector(`#${uuid.value} .el-upload__input`);
dom && dom.dispatchEvent(new MouseEvent('click'));
};
/**
* @description 文件上传之前判断
* @param rawFile 选择的文件
* */
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 图片上传错误
* */
const uploadError = () => {
ElNotification({
title: '温馨提示',
message: '图片上传失败,请您重新上传!',
type: 'error',
});
};
</script>
<style scoped lang="scss">
.is-error {
.upload {
:deep(.el-upload),
:deep(.el-upload-dragger) {
border: 1px dashed var(--el-color-danger) !important;
&:hover {
border-color: var(--el-color-primary) !important;
}
}
}
}
:deep(.disabled) {
.el-upload,
.el-upload-dragger {
cursor: not-allowed !important;
background: var(--el-disabled-bg-color);
border: 1px dashed var(--el-border-color-darker) !important;
&:hover {
border: 1px dashed var(--el-border-color-darker) !important;
}
}
}
.upload-box {
.no-border {
:deep(.el-upload) {
border: none !important;
}
}
:deep(.upload) {
.el-upload {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: v-bind(width);
height: v-bind(height);
overflow: hidden;
border: 1px dashed var(--el-border-color-darker);
border-radius: v-bind(borderRadius);
transition: var(--el-transition-duration-fast);
&:hover {
border-color: var(--el-color-primary);
.upload-handle {
opacity: 1;
}
}
.el-upload-dragger {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
padding: 0;
overflow: hidden;
background-color: transparent;
border: 1px dashed var(--el-border-color-darker);
border-radius: v-bind(borderRadius);
&:hover {
border: 1px dashed var(--el-color-primary);
}
}
.el-upload-dragger.is-dragover {
background-color: var(--el-color-primary-light-9);
border: 2px dashed var(--el-color-primary) !important;
}
.upload-image {
width: 100%;
height: 100%;
object-fit: contain;
}
.upload-empty {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: 12px;
line-height: 30px;
color: var(--el-color-info);
.el-icon {
font-size: 28px;
color: var(--el-text-color-secondary);
}
}
.upload-handle {
position: absolute;
top: 0;
right: 0;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
cursor: pointer;
background: rgb(0 0 0 / 60%);
opacity: 0;
transition: var(--el-transition-duration-fast);
.handle-icon {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 0 6%;
color: aliceblue;
.el-icon {
margin-bottom: 40%;
font-size: 130%;
line-height: 130%;
}
span {
font-size: 85%;
line-height: 85%;
}
}
}
}
}
.el-upload__tip {
line-height: 18px;
text-align: center;
}
}
</style>

View File

@ -0,0 +1,319 @@
<template>
<div class="upload-box">
<div v-for="(item, index) in fileList" class="items">
<img v-if="item.filePath" :src="item.filePath"
class="upload-image" />
<div class="upload-handle" @click.stop>
<div class="handle-icon" @click="handleEdit(index)" v-if="!self_disabled">
<el-icon :size="props.iconSize">
<Edit />
</el-icon>
</div>
<div class="handle-icon" @click="onPreview(index)">
<el-icon :size="props.iconSize">
<ZoomIn />
</el-icon>
</div>
<div class="handle-icon" @click="handleRemove(index)" v-if="!self_disabled">
<el-icon :size="props.iconSize">
<Delete />
</el-icon>
</div>
</div>
</div>
<el-upload action="#" :id="uuid" class="upload-demo my-upload-file"
:class="fileList.length > 0 && !loading ? 'success-file' : ''" :multiple="multiple" ref="uploadRef"
:disabled="loading ? true : (self_disabled || fileList.length >= props.limit)" :http-request="handleHttpUpload"
:before-upload="beforeUpload" list-type="picture-card" :limit="limit" :file-list="fileList"
:show-file-list="false" v-if="!self_disabled" :on-exceed="onExceed" :accept="props.fileType">
<el-icon v-if="!loading">
<Plus />
</el-icon>
<el-progress type="circle" v-else :percentage="progress"></el-progress>
</el-upload>
</div>
</template>
<script setup lang="ts">
import { computed,ref } from "vue";
import { ElNotification, UploadFile, UploadInstance } from "element-plus";
import type { UploadProps, UploadRequestOptions } from "element-plus";
import { Plus } from '@element-plus/icons-vue'
import { generateUUID } from "@/utils/auth";
const uploadRef = ref<UploadInstance>();
import {upload} from '@/api/common'
//
const props = defineProps({
zIndex: {
default: -1
},
multiple: {
type: Boolean,
default: false
},
btnTip: {
type: String,
default: ''
},
limit: {
type: Number,
default: undefined
},
width: {
type: String,
default: '150px'
},
height: {
type: String,
default: '150px'
},
borderRadius: {
type: String,
default: '8px'
},
fileList: {
type: Array,
required: true,
default: []
},
disabled: {
default: false
},
fileSize: {
default: 200
},
orderNo: {
default: ''
},
fileType: {
default: ""
},
name: {
default: ""
}
});
// id
const uuid = ref("id-" + generateUUID());
//
const self_disabled = computed(() => {
return props.disabled;
});
let editIndex = ''
const emit = defineEmits(["upload"]);
const progress = ref(0)
const loading = ref(false);
const handleHttpUpload = async (options: UploadRequestOptions) => {
loading.value = true;
try {
const formData = new FormData()
formData.append('file',options.file)
formData.append('name',props.name)
const res =await upload(formData)
if (props.multiple) {
let list = JSON.parse(JSON.stringify(props.fileList))
if (editIndex !== '') {
list.splice(editIndex, 1, {
url: res.fileUrl,
name: res.fileName,
filePath: res.fileUrl,
fileName: res.fileName
})
editIndex = ''
} else {
list.push({
url: res.fileUrl,
name: res.fileName,
filePath: res.fileUrl,
fileName: res.fileName
})
}
emit('upload', list)
} else {
emit("upload", res, props.zIndex);
}
} catch (error) {
ElNotification({
title: "温馨提示",
message: "上传文件失败!",
type: "error"
});
if (props.multiple) {
emit('upload', props.fileList)
} else {
uploadRef.value!.clearFiles();
emit("upload", "", props.zIndex);
}
options.onError(error as any);
} finally {
progress.value = 0
loading.value = false;
}
};
const onPreview = (index: any) => {
window.open(props.fileList[index].filePath)
}
const handleEdit = (index: any) => {
editIndex = index
const dom = document.querySelector(`#${uuid.value} .el-upload__input`);
dom && dom.dispatchEvent(new MouseEvent('click'));
}
const handleRemove = (index: any) => {
editIndex = index
if (props.multiple) {
emit("upload", props.fileList.filter((f, i) => !(editIndex == i)))
} else {
uploadRef.value!.clearFiles();
emit("upload", "" ,props.zIndex);
}
};
const onExceed = () => {
if (props.limit) {
ElNotification({
title: "温馨提示",
message: `最多支持上传${props.limit}`,
type: "warning"
});
}
};
/**
* @description 文件上传之前判断
* @param rawFile 选择的文件
* */
const beforeUpload: UploadProps["beforeUpload"] = (rawFile) => {
const imgSize = rawFile.size / 1024 / 1024 < props.fileSize;
if (!imgSize) {
ElNotification({
title: "温馨提示",
message: `上传文件大小不能超过 ${props.fileSize}M`,
type: "warning"
});
return false;
}
if (props.fileType) {
let fileType = props.fileType.replace(/\s/g, "");
fileType.split('.').join('|')
let fileIndex = rawFile.name.lastIndexOf('.')
let substrName = rawFile.name.substr(fileIndex)
if (fileType.indexOf(substrName) == -1) {
ElNotification({
title: "温馨提示",
message: "上传文件不符合所需的格式!",
type: "warning"
});
return false;
}
}
return true;
};
</script>
<style scoped lang="scss">
.success-file {
.el-upload {
.el-upload-dragger {
border-width: 3px;
border-color: var(--el-color-success) !important;
}
}
}
.my-upload-file {
.el-upload-dragger {
padding: var(--el-upload-dragger-padding-vertical);
}
.el-upload-list__item.is-success.el-list-leave-active.el-list-leave-to {
display: none;
}
.el-icon--close-tip {
display: none !important;
}
}
.el-form-item.is-error {
.el-upload-dragger {
border-width: 3px;
border-color: var(--el-color-error) !important;
}
}
::v-deep .el-upload-list__item {
transition: none !important;
}
.upload-box {
position: relative;
display: flex;
>div {
margin-right: 10px;
position: relative;
&.items {
width: v-bind(width);
height: v-bind(height);
border: 1px dashed var(--el-border-color-darker);
border-radius: v-bind(borderRadius);
}
&:hover {
.upload-handle {
opacity: 1;
}
}
}
.upload-image {
width: 100%;
height: 100%;
object-fit: contain;
}
.upload-handle {
position: absolute;
top: 0;
right: 0;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
cursor: pointer;
background: rgb(0 0 0 / 60%);
opacity: 0;
transition: var(--el-transition-duration-fast);
.handle-icon {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 0 6%;
color: aliceblue;
.el-icon {
margin-bottom: 40%;
font-size: 130%;
line-height: 130%;
}
span {
font-size: 85%;
line-height: 85%;
}
}
}
}
</style>

View File

@ -97,8 +97,15 @@
</el-form-item>
</div>
<el-form-item label="头像" prop="avatar" :rules="{ required: true, message: '请输上传头像', trigger: 'blur' }">
<BasicUpload :action="`${uploadUrl}/api/upload/uploadFile`" :list="formData.avatar?[{name:formData.avatarName,url:formData.avatar}]:[]" :headers="uploadHeaders"
:data="{ name: 'user' }" :limit="1" @upload-change="uploadChange" @delete="handleDelete"/>
<!-- <BasicUpload :action="`${uploadUrl}/api/upload/uploadFile`" :list="formData.avatar?[{name:formData.avatarName,url:formData.avatar}]:[]" :headers="uploadHeaders"
:data="{ name: 'user' }" :limit="1" @upload-change="uploadChange" @delete="handleDelete"/> -->
<UploadImg @changeFileName="(name)=>formData.avatarName=name"
:fileType=" ['image/jpeg', 'image/png', 'image/jpg', 'image/gif']"
name="user"
:fileSize="200"
v-model:image-url="formData.avatar">
<template v-slot:tip>支持扩展名: jpg png jpeg;文件大小不超过200M</template>
</UploadImg>
</el-form-item>
</el-form>
<template #footer>
@ -115,6 +122,7 @@
<script lang="ts" setup>
import { getUserDetail, userAdd, userUpdate } from '@/api/system/user';
import { BasicUpload } from '@/components/Upload';
import UploadImg from '@/components/Upload/Image.vue';
import chinaArea from '@/components/ChinaArea/index.vue';
import { onMounted, reactive, shallowRef } from "vue";
import { getRoleAllList } from '@/api/system/role';
@ -219,6 +227,7 @@ const optionData = reactive({
});
function uploadChange(data: string[]) {
formData.avatar = data.fileUrl;
formData.avatarName =data.fileName
}