封装el-upload组件,用于上传图片和视频

ops/2024/10/18 7:56:27/

使用环境 vue3+element-ui plus
需要根据后端返回结构修改的函数:onPreview onRemove onSuccess

组件使用

基本使用

在这里插入图片描述
源代码:

<script setup>
import AutoUploadFile from '@/components/auto-upload-file/index.vue'
function change(urls){console.log(urls)
}
</script><template><AutoUploadFile @change="change"/>
</template><style lang="scss" scoped>
</style>

初始文件列表回显

在这里插入图片描述
源代码:

<script setup>
import AutoUploadFile from '@/components/auto-upload-file/index.vue'
import {ref} from "vue";const initUrls = ref(['http://127.0.0.1:9090/file/local-plus/6700f235df13a72064bf9167.png'
])function change(urls) {console.log(urls)
}
</script><template><AutoUploadFile :init-file-urls="initUrls" accept=".jpg,.jpeg,.png" @change="change"></AutoUploadFile>
</template><style lang="scss" scoped>
</style>

定义上传格式

如果有mp4类型,文件展示列表就会变为text

在这里插入图片描述
源代码:

<script setup>
import AutoUploadFile from '@/components/auto-upload-file/index.vue'
function change(urls){console.log(urls)
}
</script><template><AutoUploadFile accept=".jpg,.jpeg,.png,.mp4" :max-size="100" @change="change"/>
</template><style lang="scss" scoped>
</style>

自定义上传按钮样式

在这里插入图片描述
源代码:

<script setup>
import AutoUploadFile from '@/components/auto-upload-file/index.vue'
function change(urls){console.log(urls)
}
</script><template><AutoUploadFile accept=".jpg,.jpeg,.png,.mp4" :max-size="100" @change="change"><el-button>自定义上传样式</el-button></AutoUploadFile>
</template><style lang="scss" scoped>
</style>

组件属性

属性名属性类型默认值是否必填说明
initFileUrlsArray[]用于上传列表的回显,接收外部初始化url数组
listTypeStringpicture-card上传列表展示格式。可选项:picture-card/picture/text , 但是如果accept允许mp4,那么listType就会自动转化为text
actionString#上传文件时的接口服务
headersObject{}请求头
nameStringfile提交文件时的字段名
withCredentialsBooleantrue是否支持cookie凭证信息
showFileListBooleantrue是否展示上传列表
acceptString“.jpg,.jpeg,.png”可以上传的文件类型
limitNumber5允许上传的最大文件数量
maxSizeNumber5最大文件大小,单位MB
tipPrefixString“”提示信息前缀
showTipBooleantrue是否展示提示信息
showOverflowTooltipBooleantruetip过长是否使用省略号显示
multipleBooleantrue可以多选文件
autoUploadBooleantrue默认自动上传
sizeString100pxpicture-card的尺寸大小

组件事件

事件名事件参数列表说明
onProgress(e,file,fileList)用于监控文件上传进度
change(urls)上传列表改变时的回调

组件暴露方法

方法名参数列表说明
clearFiles()清空文件列表
submit()用于手动提交

组件插槽

插槽名插槽回显参数说明
default上传文件时的点击区域,用于自定义样式
file{ file }文件列表样式,用于自定义缩略图
trigger用于手动提交,只选择文件,不发起提交请求的插槽

组件源码:(auto-upload-file.vue)

<!--需要根据后端返回结构修改的函数:onPreview onRemove onSuccess -->
<script setup>
import {computed, onMounted, onUpdated, ref} from "vue";
import {ElMessage} from "element-plus";const prop = defineProps({// 文件列表initFileUrls: {type: Array,default: []},// 展示格式listType: {type: String,default: 'picture-card'},// 上传文件的默认接口action: {type: String,default: 'http://localhost:9090/upload/file'},// 请求头(添加token等)headers: {type: Object,default: {}},// 上传时的文件名(需要与后端接收时的字段保持一致)name: {type: String,default: 'file'},// 默认支持cookie凭证信息withCredentials: {type: Boolean,default: true},// 默认展示上传文件列表showFileList: {type: Boolean,default: true},// 可接受文件的类型accept: {type: String,default: '.jpg,.jpeg,.png'},// 允许上传的最大文件数量limit: {type: Number,default: 5},// 单位MBmaxSize: {type: Number,default: 5},// 提示前缀tipPrefix: {type: String,default: ''},// 是否展示提示showTip: {type: Boolean,default: true},// tip过长使用省略号显示showOverflowTooltip: {type: Boolean,default: true},// 可以多选文件multiple: {type: Boolean,default: true},// 默认自动上传autoUpload: {type: Boolean,default: true},// picture-card尺寸大小size: {type: String,default: '6.25rem'}
})const emit = defineEmits(['onProgress', 'change'])
defineExpose({clearFiles,submit
})// el-upload使用的文件列表
const fileList = ref(prop.initFileUrls.map(item => {return {name: getFileName(item),url: item}
}))const uploadRef = ref()// 存放后端返回的url,及初始化url
const urls = ref([...prop.initFileUrls])// 如果允许上传视频,则默认只能使用text显示上传列表
const listTypeCmp = computed(() => {return prop.accept.indexOf('mp4') !== -1 ? 'text' : prop.listType
})// 提示信息
const tip = computed(() => {return `${prop.tipPrefix ? prop.tipPrefix + ',' : ''}文件类型:${prop.accept.replaceAll(',', '/').replaceAll('.', '')},文件大小不能超过:${prop.maxSize}MB`
})// 文件上传之前的钩子
function beforeUpload(e) {const MB = e.size / (1024 * 1024)if (MB > prop.maxSize) {ElMessage.error(`文件的大小不能超过:${prop.maxSize}MB`)return false}
}// 上传成功的回调(根据后端返回值不同需要略作修改)
function onSuccess(e, file) {urls.value.push(e)emit('change', urls.value)
}const dialogFileUrl = ref()
const dialogVisible = ref(false)// 预览图片(根据后端返回值不同需要略作修改)
function onPreview(e) {dialogFileUrl.value = e.response || e.urldialogVisible.value = true
}// 移除文件(根据后端返回值不同需要略作修改)
function onRemove(e) {urls.value = urls.value.filter(item => item !== (e.response || e.url))emit('change', urls.value)
}// 超出最大文件限制时,执行的钩子函数
function onExceed(e) {ElMessage.error(`超出要求的文件最大数量:${prop.limit}`)
}// 文件上传失败时的回调
function onError() {ElMessage.error('文件上传失败')
}// 上传进度回调
function onProgress(e, file, fileList) {emit('onProgress', e, file, fileList)
}// 清空文件列表
function clearFiles() {uploadRef.value.clearFiles()urls.value = []emit('change', urls.value)
}// 手动提交
function submit() {uploadRef.value.submit()
}// 获取后缀
function getSuffix(url) {return url.substring(url.lastIndexOf('.') + 1)
}// 获取文件名
function getFileName(url) {return url.substring(url.lastIndexOf('/') + 1)
}// 阻止点击tip时触发的上传行为
function preventClick(event) {event.stopPropagation()
}// 初始化picture-card大小
function initSize() {const uploadListItem = document.querySelector('.el-upload-list--picture-card')const uploadPictureCard = document.querySelector('.el-upload--picture-card')if (uploadListItem) {uploadListItem.style.setProperty('--el-upload-list-picture-card-size', prop.size)}if (uploadPictureCard) {uploadPictureCard.style.setProperty('--el-upload-picture-card-size', prop.size)if (listTypeCmp.value==='picture-card'){uploadPictureCard.style['margin-bottom']='1.56rem'}}
}// 动态处理展示样式
function handleStyle() {initSize()
}onUpdated(() => {handleStyle()
})
onMounted(() => {handleStyle()
})</script><template><el-uploadref="uploadRef"class="upload-box"v-model:file-list="fileList":list-type="listTypeCmp":action="action":headers="headers":with-credentials="withCredentials":name="name":show-file-list="showFileList":before-upload="beforeUpload":on-success="onSuccess":on-remove="onRemove":on-preview="onPreview":accept="accept":limit="limit":on-exceed="onExceed":on-error="onError":on-progress="onProgress":auto-upload="autoUpload":multiple="multiple"><template #default v-if="autoUpload"><div class="upload"><div class="upload-default"><slot><el-icon v-if="listTypeCmp==='picture-card'"style="width: 100%;height: 100%;font-size: 1.88rem;color: #888888"><Plus/></el-icon><el-button v-else>上传文件</el-button></slot></div><div v-if="listTypeCmp==='picture-card' && showTip" class="upload-tip abs-tip" @click="preventClick"><div class="tip-div" :title="tip":class="{'text-overflow-ellipsis':showOverflowTooltip}"><span>{{ tip }}</span></div></div></div></template><template #tip v-if="listTypeCmp!=='picture-card' && showTip"><div class="upload-tip" @click="preventClick"><div class="tip-div" :title="tip":class="{'text-overflow-ellipsis':showOverflowTooltip}"><span>{{ tip }}</span></div></div></template><!--    自定义缩略图--><template #file="{file}"><slot name="file" :file="file"></slot></template><template #trigger v-if="!autoUpload"><slot name="trigger"></slot></template></el-upload><!--文件预览--><el-dialog v-model="dialogVisible" width="80%"><video style="height: 100%;width: 100%" v-if="getSuffix(dialogFileUrl)==='mp4'" :src="dialogFileUrl" controls/><el-image v-else style="height: 80vh" w-full :src="dialogFileUrl" alt="Preview Image"/></el-dialog>
</template><style lang="scss" scoped>.upload-box {box-sizing: border-box;.upload {position: relative;height: 100%;width: 100%;display: flex;justify-content: center;align-items: center;.abs-tip{position: absolute;bottom: -1.88rem;left: 0;}}.upload-tip {width: 100%;.tip-div {width: 100%;cursor: pointer;color: red;font-weight: 200;font-size: 0.75rem;}.text-overflow-ellipsis {display: inline-block;overflow: hidden;white-space: nowrap; /* 不换行 */text-overflow: ellipsis; /* 超出部分显示为省略号 */}}
}
</style>

http://www.ppmy.cn/ops/122200.html

相关文章

python爬虫 - 初识requests模块

&#x1f308;个人主页&#xff1a;https://blog.csdn.net/2401_86688088?typeblog &#x1f525; 系列专栏&#xff1a;https://blog.csdn.net/2401_86688088/category_12797772.html 前言 requests 是一个用于发送 HTTP 请求的 Python 库&#xff0c;设计简单且功能强大&am…

Python知识点:如何使用AWS Greengrass与Python进行边缘计算

开篇&#xff0c;先说一个好消息&#xff0c;截止到2025年1月1日前&#xff0c;翻到文末找到我&#xff0c;赠送定制版的开题报告和任务书&#xff0c;先到先得&#xff01;过期不候&#xff01; 如何使用AWS Greengrass与Python进行边缘计算 边缘计算是云计算的有力补充&…

《重生到现代之从零开始的C语言生活》—— 内存函数

memcpy函数 和strncpy的用法基本一致 而不一样的是&#xff0c;size_t num是从源内存向后复制num个字节的数据到目标内存 但是如果有重叠的部分&#xff0c;就不能用memcpy了我们得用memmove memmove函数 **memcpy和memmove基本一致&#xff0c;**但是区别是如果源内存和目标…

js拼接html代码在线工具

具体请前往&#xff1a;在线Html转Js--将Html代码转成javascript动态拼接代码并保持原有格式

C# (.net6)实现Redis发布和订阅简单案例

概念&#xff1a; 在 .NET 6 中使用 Redis 的/订发布阅模式。发布/订阅&#xff08;Pub/Sub&#xff09;是 Redis 支持的一种消息传递模式&#xff0c;其中一个或多个发布者向一个或多个订阅者发送消息,Redis 客户端可以订阅任意数量的频道。 多个客户端可以订阅一个相同的频道…

Pikachu-Sql Inject-insert/update/delete注入

insert 注入 插入语句 insert into tables values(value1,value2,value3); 如&#xff1a;插入用户表 insert into users (id,name,password) values (id,username,password); 当点击注册 先判断是否有SQL注入漏洞&#xff0c;经过判断之后发现存在SQL漏洞。构造insert的pa…

结合大语言模型的机械臂抓取操作简单介绍

一、大语言模型与机械臂抓取的基本操作 1. 大语言模型简介 大语言模型是基于深度学习技术构建的自然语言处理模型&#xff0c;能够生成、理解和处理文本信息。这些模型通过训练大量的文本数据&#xff0c;学习语法、上下文和常识&#xff0c;能够执行多种任务&#xff0c;如文…

【2024最新】华为HCIE认证考试流程

HCIE是华为认证体系中最高级别的ICT技术认证&#xff0c;表示通过认证的人具有ICT领域专业知识和丰富实践经验。 HCIE认证方向&#xff1a;最高认证级别HCIE的技术方向有13个 下面以HCIE-Datacom为例给大家介绍一下&#xff1a; HCIE-Datacom认证考试流程&#xff1a; 1.笔试…