调整上传图片尺寸

This commit is contained in:
zjl 2024-10-08 14:08:10 +08:00
parent fb86d5f8fd
commit 08230c5343
5 changed files with 959 additions and 942 deletions

View File

@ -1,365 +1,365 @@
<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]"
/>
</div>
<Cropper
v-model:visible="cropperVisible"
v-if="cropperVisible"
:cropperSize="cropperSize"
:oImg="oImg"
@success="cropperSuccess"
:fileName="fileName"
></Cropper>
<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]"
/>
</div>
<Cropper
v-model:visible="cropperVisible"
v-if="cropperVisible"
:cropperSize="cropperSize"
:oImg="oImg"
@success="cropperSuccess"
:fileName="fileName"
/>
</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'
import Cropper from '@/components/Upload/cropper.vue'
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';
import Cropper from '@/components/Upload/cropper.vue';
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;
cropper:Boolean,
cropperSize?:Object
}
const cropperVisible=ref(false)
//
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:'',
cropper:false,
cropperSize:null
});
// id
const uuid = ref('id-' + generateUUID());
const viewImg=()=>{
if(props.imageUrl.indexOf('.pdf')<0){
imgViewVisible.value = true
}else{
window.open(props.imageUrl)
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;
cropper: Boolean;
cropperSize?: Object;
}
}
//
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;
});
const cropperVisible = ref(false);
//
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: '120px',
width: '120px',
borderRadius: '8px',
name: '',
cropper: false,
cropperSize: null,
});
/**
* @description 图片上传
* @param options upload 所有配置项
* */
interface UploadEmits {
(e: 'update:imageUrl', value: string): void,
(e: 'changeFileName', value: string): void;
}
// id
const uuid = ref('id-' + generateUUID());
const fileName=ref('')
const oImg=ref('')
const emit = defineEmits<UploadEmits>();
const loading=ref(false)
const progress=ref(0)
const cropperSuccess=(fileChile:any)=>{
actionFile(fileChile)
}
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)
emit('update:imageUrl',res.fileUrl);
emit('changeFileName',res.originalName)
// 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 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 handleHttpUploadOptions=ref({})
const fileName = ref('');
const oImg = ref('');
const emit = defineEmits<UploadEmits>();
const loading = ref(false);
const progress = ref(0);
const cropperSuccess = (fileChile: any) => {
actionFile(fileChile);
};
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);
emit('update:imageUrl', res.fileUrl);
emit('changeFileName', res.originalName);
// 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 handleHttpUpload = async (options: UploadRequestOptions) => {
handleHttpUploadOptions.value=options
if(props.cropper){
fileName.value= options.file.name
let reader = new FileReader();
reader.readAsDataURL(options.file);
let img = new Image();
reader.onload = function (e) {
img.src = this.result;
img.onload = function () {
let base = e.target.result;
oImg.value= base;
event.target.value = "";
cropperVisible.value = true;
const handleHttpUploadOptions = ref({});
const handleHttpUpload = async (options: UploadRequestOptions) => {
handleHttpUploadOptions.value = options;
if (props.cropper) {
fileName.value = options.file.name;
let reader = new FileReader();
reader.readAsDataURL(options.file);
let img = new Image();
reader.onload = function (e) {
img.src = this.result;
img.onload = function () {
let base = e.target.result;
oImg.value = base;
event.target.value = '';
cropperVisible.value = true;
};
};
};
return
}
actionFile(options.file)
};
return;
}
actionFile(options.file);
};
/**
* @description 删除图片
* */
const deleteImg = () => {
emit('update:imageUrl', '');
emit('changeFileName','')
};
/**
* @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 编辑图片
* */
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 文件上传之前判断
* @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',
});
};
/**
* @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;
}
}
.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: 90%;
height: 90%;
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

@ -1,8 +1,7 @@
<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" />
<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">
@ -21,300 +20,314 @@
</div>
</div>
</div>
<el-upload action="#" :id="uuid" class="upload-demo my-upload-images"
: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-upload
action="#"
:id="uuid"
class="upload-demo my-upload-images"
: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-progress type="circle" v-else :percentage="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";
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 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 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 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.originalName,
filePath: res.fileUrl,
fileName: res.originalName
})
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.originalName,
filePath: res.fileUrl,
fileName: res.originalName,
});
editIndex = '';
} else {
list.push({
url: res.fileUrl,
name: res.originalName,
filePath: res.fileUrl,
fileName: res.originalName,
});
}
emit('upload', list, props.zIndex);
} else {
list.push({
url: res.fileUrl,
name: res.originalName,
filePath: res.fileUrl,
fileName: res.originalName
})
emit('upload', res, props.zIndex);
}
emit('upload', list,props.zIndex)
} else {
emit("upload", res, props.zIndex);
} catch (error) {
ElNotification({
title: '温馨提示',
message: '上传文件失败!',
type: 'error',
});
if (props.multiple) {
emit('upload', props.fileList, props.zIndex);
} else {
uploadRef.value!.clearFiles();
emit('upload', '', props.zIndex);
}
options.onError(error as any);
} finally {
progress.value = 0;
loading.value = false;
}
} catch (error) {
ElNotification({
title: "温馨提示",
message: "上传文件失败!",
type: "error"
});
};
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,props.zIndex)
emit(
'upload',
props.fileList.filter((f, i) => !(editIndex == i)),
props.zIndex,
);
} else {
uploadRef.value!.clearFiles();
emit("upload", "", props.zIndex);
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)),props.zIndex)
} 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) {
const onExceed = () => {
if (props.limit) {
ElNotification({
title: "温馨提示",
message: "上传文件不符合所需的格式!",
type: "warning"
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;
}
}
return true;
};
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 {
.success-file {
.el-upload {
.el-upload-dragger {
border-width: 3px;
border-color: var(--el-color-success) !important;
}
}
}
.my-upload-images {
.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-success) !important;
border-color: var(--el-color-error) !important;
}
}
}
.my-upload-images {
.el-upload-dragger {
padding: var(--el-upload-dragger-padding-vertical);
:deep(.el-upload-list__item) {
transition: none !important;
}
.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;
}
}
:deep(.el-upload-list__item){
transition: none !important;
}
.upload-box {
position: relative;
display: flex;
flex-wrap: wrap;
>div {
margin-right: 10px;
margin-bottom: 10px;
.upload-box {
position: relative;
display: flex;
flex-wrap: wrap;
> div {
margin-right: 10px;
margin-bottom: 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);
}
&.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;
&:hover {
.upload-handle {
opacity: 1;
}
}
}
}
.upload-image {
width: 100%;
height: 100%;
object-fit: contain;
}
.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 {
.upload-handle {
position: absolute;
top: 0;
right: 0;
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 0 6%;
color: aliceblue;
width: 100%;
height: 100%;
cursor: pointer;
background: rgb(0 0 0 / 60%);
opacity: 0;
transition: var(--el-transition-duration-fast);
.el-icon {
margin-bottom: 40%;
font-size: 130%;
line-height: 130%;
}
.handle-icon {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 0 6%;
color: aliceblue;
span {
font-size: 85%;
line-height: 85%;
.el-icon {
margin-bottom: 40%;
font-size: 130%;
line-height: 130%;
}
span {
font-size: 85%;
line-height: 85%;
}
}
}
}
}
</style>

View File

@ -1,35 +1,35 @@
<template>
<el-dialog
v-model="props.visible"
title="图片裁剪"
:append-to-body="true"
class="cropper_model_dlg"
width="500"
:close-on-click-modal="false"
:before-close="dialogClose"
v-model="props.visible"
title="图片裁剪"
:append-to-body="true"
class="cropper_model_dlg"
width="500"
:close-on-click-modal="false"
:before-close="dialogClose"
>
<div class="cropper_content">
<div class="cropper" style="text-align: center;">
<div class="cropper" style="text-align: center">
<vueCropper
ref="cropperRef"
:img="options.img"
:outputSize="options.outputSize"
:outputType="options.outputType"
:info="options.info"
:canScale="options.canScale"
:autoCrop="options.autoCrop"
:autoCropWidth="options.autoCropWidth"
:autoCropHeight="options.autoCropHeight"
:fixed="options.fixed"
:maximgSize="options.maximgSize"
:fixedBox="options.fixedBox"
:enlarge="options.enlarge"
:fixedNumber="options.fixedNumber"
></vueCropper>
ref="cropperRef"
:img="options.img"
:outputSize="options.outputSize"
:outputType="options.outputType"
:info="options.info"
:canScale="options.canScale"
:autoCrop="options.autoCrop"
:autoCropWidth="options.autoCropWidth"
:autoCropHeight="options.autoCropHeight"
:fixed="options.fixed"
:maximgSize="options.maximgSize"
:fixedBox="options.fixedBox"
:enlarge="options.enlarge"
:fixedNumber="options.fixedNumber"
/>
</div>
<div class="cropper_btns">
<el-button @click="rotateLeft" icon="RefreshLeft" size="mini" title="左旋转"></el-button>
<el-button @click="rotateRight" icon="RefreshRight" size="mini" title="右旋转"></el-button>
<el-button @click="rotateLeft" icon="RefreshLeft" size="mini" title="左旋转" />
<el-button @click="rotateRight" icon="RefreshRight" size="mini" title="右旋转" />
<el-button @click="changeScale(1)" size="mini" title="放大">+</el-button>
<el-button @click="changeScale(-1)" size="mini" title="缩小">-</el-button>
</div>
@ -44,154 +44,154 @@
</template>
<script lang="ts" setup>
import VueCropper from "vue-cropper/src/vue-cropper.vue";
import { ref, reactive} from 'vue';
import VueCropper from 'vue-cropper/src/vue-cropper.vue';
import { ref, reactive } from 'vue';
const props = defineProps({
visible: {
type: Boolean,
required: true,
default: false
},
cropperSize: {
type: Object,
default() {
return null;
const props = defineProps({
visible: {
type: Boolean,
required: true,
default: false,
},
cropperSize: {
type: Object,
default() {
return null;
},
},
oImg: {
type: String,
default: '',
},
fileName: {
type: String,
default: '',
},
folder: {
type: String,
default: '',
},
});
const dialogClose = () => {
emit('update:visible', false);
};
const options = reactive({
img: props.oImg, //
outputSize: 1, //
outputType: 'png', //
info: true, //
canScale: true, //
autoCrop: true, //
autoCropWidth: props.cropperSize ? props.cropperSize.width : 200, //
autoCropHeight: props.cropperSize ? props.cropperSize.height : 200, //
fixed: false, //
fixedNumber: [1, 1], //
full: true, //
fixedBox: true, //
canMove: true, //
canMoveBox: true, //
original: true, //
centerBox: false, //
high: false, // dpr
infoTrue: true, // truefalse
maximgSize: 100, //
enlarge: 1, //
mode: 'contain', // (contain, cover, 100px, 100% auto)
});
const cropperRef = ref();
const addImgLoading = ref(false);
//
const rotateLeft = () => {
cropperRef.value.rotateLeft();
};
//
const rotateRight = () => {
cropperRef.value.rotateRight();
};
//
const changeScale = (num: any) => {
num = num || 1;
cropperRef.value.changeScale(num);
};
const emit = defineEmits(['success', 'update:visible']);
// base64
const dataURLtoFile = (dataurl: any, filename: any) => {
let arr = dataurl.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let len = bstr.length;
let u8arr = new Uint8Array(len);
while (len--) {
u8arr[len] = bstr.charCodeAt(len);
}
},
oImg: {
type: String,
default: ""
},
fileName: {
type: String,
default: ""
},
folder: {
type: String,
default: ""
}
});
return new File([u8arr], filename, { type: mime });
};
const dialogClose = () => {
emit("update:visible", false);
};
const options = reactive({
img: props.oImg, //
outputSize: 1, //
outputType: "png", //
info: true, //
canScale: true, //
autoCrop: true, //
autoCropWidth: props.cropperSize ? props.cropperSize.width : 200, //
autoCropHeight: props.cropperSize ? props.cropperSize.height : 200, //
fixed: false, //
fixedNumber: [1, 1], //
full: true, //
fixedBox: true, //
canMove: true, //
canMoveBox: true, //
original: true, //
centerBox: false, //
high: false, // dpr
infoTrue: true, // truefalse
maximgSize: 100, //
enlarge: 1, //
mode: "contain" // (contain, cover, 100px, 100% auto)
});
const cropperRef = ref();
const submit = () => {
cropperRef.value.getCropData((fileData) => {
let file = dataURLtoFile(fileData, props.fileName);
emit('update:visible', false);
emit('success', file);
});
};
const addImgLoading = ref(false);
//
const rotateLeft = () => {
cropperRef.value.rotateLeft();
};
//
const rotateRight = () => {
cropperRef.value.rotateRight();
};
//
const changeScale = (num: any) => {
num = num || 1;
cropperRef.value.changeScale(num);
};
const emit = defineEmits(["success", "update:visible"]);
// base64
const dataURLtoFile=(dataurl:any, filename:any)=> {
let arr = dataurl.split(",");
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let len = bstr.length;
let u8arr = new Uint8Array(len);
while (len--) {
u8arr[len] = bstr.charCodeAt(len);
}
return new File([u8arr], filename, {type: mime});
}
const submit=()=>{
cropperRef.value.getCropData(fileData => {
let file = dataURLtoFile(fileData, props.fileName);
emit("update:visible", false);
emit('success',file)
})
}
//
defineExpose({});
//
defineExpose({});
</script>
<style lang="scss">
.cropper_model_dlg {
.el-dialog__body {
padding: 0px 20px 60px !important
}
.cropper_model_dlg {
.el-dialog__body {
padding: 0px 20px 60px !important;
}
.cropper_content {
margin: 0 auto;
display: flex;
flex-direction: column;
align-items: center;
}
.cropper_content {
margin: 0 auto;
display: flex;
flex-direction: column;
align-items: center;
}
.add-img {
opacity: 0;
position: absolute;
width: 80px;
height: 28px;
top: 0px;
left: 0px;
}
.add-img {
opacity: 0;
position: absolute;
width: 80px;
height: 28px;
top: 0px;
left: 0px;
}
.cropper {
width: 400px;
height: 400px;
background: yellow;
}
.cropper {
width: 400px;
height: 400px;
background: yellow;
}
.cropper500 {
width: 600px;
height: 600px;
background: yellow;
border: 1px solid #e3e3e3;
}
.cropper500 {
width: 600px;
height: 600px;
background: yellow;
border: 1px solid #e3e3e3;
}
.cropper_right {
width: 520px;
text-align: center;
}
.cropper_right {
width: 520px;
text-align: center;
}
.cropper_preview {
margin: 0 auto;
display: inline-block;
border: 1px solid #ddd;
}
.cropper_preview {
margin: 0 auto;
display: inline-block;
border: 1px solid #ddd;
}
.cropper_btns {
margin-top: 20px;
.cropper_btns {
margin-top: 20px;
}
}
}
</style>

View File

@ -1,28 +1,28 @@
<template>
<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"
:http-request="handleHttpUpload"
:file-list="fileList"
:on-preview="onPreview"
:on-remove="handleRemove"
:before-upload="beforeUpload"
:show-file-list="showFileList"
:drag="isBtn?false:true"
:limit="limit"
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"
:http-request="handleHttpUpload"
:file-list="fileList"
:on-preview="onPreview"
:on-remove="handleRemove"
:before-upload="beforeUpload"
:show-file-list="showFileList"
:drag="isBtn ? false : true"
:limit="limit"
>
<template v-if="isBtn">
<el-tooltip
v-if="isBtn&&btnTip"
class="box-item"
effect="dark"
:content="btnTip"
placement="top"
v-if="isBtn && btnTip"
class="box-item"
effect="dark"
:content="btnTip"
placement="top"
>
<el-button icon="Upload" type="primary">点击上传</el-button>
</el-tooltip>
@ -30,197 +30,201 @@
</template>
<template v-else>
<el-icon class="el-icon--upload">
<Finished style="color: var(--el-color-success)" v-if="fileList.length>0&&!loading"/>
<upload-filled v-else/>
<Finished style="color: var(--el-color-success)" v-if="fileList.length > 0 && !loading" />
<upload-filled v-else />
</el-icon>
<div v-if="!self_disabled" class="el-upload__text">{{loading?'上传中':(fileList.length>0?'上传成功':'点击或将文件拖拽到这里上传')}}</div>
<div v-if="!self_disabled" class="el-upload__text">{{
loading ? '上传中' : fileList.length > 0 ? '上传成功' : '点击或将文件拖拽到这里上传'
}}</div>
</template>
<template #tip>
<template v-if="!isBtn">
<div v-if="props.fileType" class="el-upload__tip">支持扩展名{{ props.fileType }}</div>
<div v-if="props.multiple && props.limit" class="el-upload__tip">最多上传{{props.limit}}个文件</div>
<div v-if="props.multiple && props.limit" class="el-upload__tip"
>最多上传{{ props.limit }}个文件</div
>
</template>
</template>
</el-upload>
</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 {generateUUID} from "@/utils/auth";
import { computed, ref } from 'vue';
import { ElNotification, UploadFile, UploadInstance } from 'element-plus';
import type { UploadProps, UploadRequestOptions } from 'element-plus';
import { generateUUID } from '@/utils/auth';
const uploadRef = ref<UploadInstance>();
import {upload} from '@/api/common'
const uploadRef = ref<UploadInstance>();
import { upload } from '@/api/common';
//
const props = defineProps({
zIndex: {
default: -1
},
multiple: {
type: Boolean,
default: false
},
isBtn: {
type: Boolean,
default: false
},
showFileList: {
type: Boolean,
default: true
},
btnTip: {
type: String,
default: ''
},
limit: {
type: Number,
default: undefined
},
fileList: {
type: Array,
required: true,
default: []
},
disabled: {
default: false
},
fileSize: {
default: 200
},
orderNo: {
default: ''
},
fileType: {
default: ""
},
name: {
default: ""
}
});
//
const props = defineProps({
zIndex: {
default: -1,
},
multiple: {
type: Boolean,
default: false,
},
isBtn: {
type: Boolean,
default: false,
},
showFileList: {
type: Boolean,
default: true,
},
btnTip: {
type: String,
default: '',
},
limit: {
type: Number,
default: undefined,
},
fileList: {
type: Array,
required: true,
default: [],
},
disabled: {
default: false,
},
fileSize: {
default: 200,
},
orderNo: {
default: '',
},
fileType: {
default: '',
},
name: {
default: '',
},
});
// id
const uuid = ref("id-" + generateUUID());
// id
const uuid = ref('id-' + generateUUID());
//
const self_disabled = computed(() => {
return props.disabled;
});
//
const self_disabled = computed(() => {
return props.disabled;
});
const emit = defineEmits(['upload']);
const emit = defineEmits(["upload"]);
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))
list.push({
url: res.fileUrl,
name: res.originalName,
filePath: res.fileUrl,
fileName: res.originalName,
})
emit('upload', list,props.zIndex)
}else{
emit("upload", res.fileUrl,res.originalName,props.zIndex);
}
} catch (error) {
ElNotification({
title: "温馨提示",
message: "上传文件失败!",
type: "error"
});
if(props.multiple){
emit('upload', props.fileList,props.zIndex)
}else{
uploadRef.value!.clearFiles();
emit("upload", "", "",props.zIndex);
}
options.onError(error as any);
} finally {
loading.value = false;
}
};
const onPreview=(uploadFile: UploadFile)=> {
window.open( uploadFile?.url)
}
const handleRemove: UploadProps["onRemove"] = (file:any) => {
if(props.multiple){
emit("upload",props.fileList.filter((f) => !(f === file.url)),props.zIndex)
}else{
uploadRef.value!.clearFiles();
emit("upload", "", "", props.zIndex);
}
};
/**
* @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"
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));
list.push({
url: res.fileUrl,
name: res.originalName,
filePath: res.fileUrl,
fileName: res.originalName,
});
emit('upload', list, props.zIndex);
} else {
emit('upload', res.fileUrl, res.originalName, props.zIndex);
}
} catch (error) {
ElNotification({
title: '温馨提示',
message: '上传文件失败!',
type: 'error',
});
if (props.multiple) {
emit('upload', props.fileList, props.zIndex);
} else {
uploadRef.value!.clearFiles();
emit('upload', '', '', props.zIndex);
}
options.onError(error as any);
} finally {
loading.value = false;
}
};
const onPreview = (uploadFile: UploadFile) => {
window.open(uploadFile?.url);
};
const handleRemove: UploadProps['onRemove'] = (file: any) => {
if (props.multiple) {
emit(
'upload',
props.fileList.filter((f) => !(f === file.url)),
props.zIndex,
);
} else {
uploadRef.value!.clearFiles();
emit('upload', '', '', props.zIndex);
}
};
/**
* @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;
}
}
return true;
};
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 lang="scss">
.success-file {
.el-upload {
.el-upload-dragger {
border-width: 3px;
border-color: var(--el-color-success) !important;
.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);
.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-upload-list__item.is-success.el-list-leave-active.el-list-leave-to{
display: none;
.el-form-item.is-error {
.el-upload-dragger {
border-width: 3px;
border-color: var(--el-color-error) !important;
}
}
.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;
}
}
</style>

View File

@ -70,7 +70,7 @@
const showModal = ref(false);
const previewUrl = ref('');
const fileList = computed(() => {
const fileList = computed(() => {
return props.list;
});