当前位置: 首页 > news >正文

el-upload上传文件自定义

业务针对性高
主要是应用在表单上传,通过文件上传返回地址,需要与表单参数一并提交

默认上传

通用组件,直接调用,案例:需后端提供接口minio上传,返回url地址
补充上传后文件点击跳转查阅
补充上传地址的header参数
在这里插入图片描述

<!-- 针对VITE_UPLOAD_URL地址上传 通用 -->
<template><el-uploadref="uploadRef":action="uploadUrl"v-model:file-list="fileList":auto-upload="true":disabled="formLoading":headers="uploadHeaders":limit="props.limit":on-change="handleChange":on-error="submitFormError":on-exceed="handleExceed":on-success="submitFormSuccess":accept="props.accept"><template #trigger><el-button type="primary">{{ props.name }}</el-button></template><template #tip><div class="el-upload__tip text-red">{{ props.tips }}</div></template><template #file="{ file, index }"><div class="flex items-center gap-4"><el-link :href="file.response?.data" target="_blank" :underline="false" class="text-12px">{{ file.name }}</el-link><Iconclass="mt-2px cursor-pointer"color="var(--el-color-danger)"@click="deleteFile(index)"icon="ep:close"/></div></template></el-upload>
</template>
<script lang="ts" setup>
import { getAccessToken, getTenantId } from '@/utils/auth'
const props = defineProps({name: {type: String,default: () => {return '上传文件'}},size: {require: false,type: Number,default: () => {return 5}},limit: {require: false,type: Number,default: () => {return 1}},tips: {require: false,type: String,default: () => {return '支持图片格式(JPG、PNG)和PDF文件,最大5MB'}},accept: {require: false,type: String,default: () => {return '.jpeg, .jpg, .png, .pdf'}}
})
const uploadUrl = import.meta.env.VITE_UPLOAD_URL
const message = useMessage() // 消息弹窗
const emit = defineEmits(['success', 'delete'])
const uploadHeaders = ref({Authorization: 'Bearer ' + getAccessToken(),'tenant-id': getTenantId()
})
const formLoading = ref(false) // 表单的加载中
const fileList = ref([] as any) // 文件列表
const uploadRef = ref()/** 处理上传的文件发生变化 */
const handleChange = (file) => {const fileName = file.nameconst fileType = fileName.substring(fileName.lastIndexOf('.'))if (props.accept.indexOf(fileType) === -1) {message.warning('上传的文件不符合所需的格式!')fileList.value.splice(-1)return}const maxSize = props.sizeconst size = maxSize * 1024 * 1024if (file.size > size) {unref(uploadRef)?.clearFiles()message.warning('上传文件大小不超过' + props.size + 'MB')return}
}
/** 文件数超出提示 */
const handleExceed = (): void => {message.error('最多只能上传' + props.limit + '份文件!')
}
/** 上传错误提示 */
const submitFormError = (): void => {unref(uploadRef)?.clearFiles()message.error('文件上传失败,请您重新上传!')
}
/** 文件上传成功处理 */
const submitFormSuccess = (res) => {emit('success', res.data)
}
const deleteFile = (index) => {emit('delete', fileList.value.length)fileList.value.splice(index, 1)
}
</script>
<style lang="scss" scoped>
:deep(.el-upload-list__item-info) {max-width: 350px;
}
</style>

案例使用

<el-form-item label="证书文件" prop="url"><uploadref="uploadRef"@success="getFileUrl"@delete="deleteFile"/></el-form-item>
const getFileUrl = (url: string) => {// TODO
}
const deleteFile = async (index: number) => {// TODO
}

取消默认上传

自定义上传地址
案例:点击按钮等才调用上传功能,利用FormData表单提交文件

<template><el-uploadref="uploadRef"v-model:file-list="fileList"action="#":auto-upload="false":disabled="formLoading":limit="1":on-change="handleChange":on-remove="hanldeRemove":on-exceed="handleExceed"accept=".jpg, .png, .jpeg, .pdf, .doc, .docx"><template #trigger><el-button type="primary">上传文件</el-button></template><template #tip><div class="el-upload__tip text-red">请上传大小不超过{{ props.size }}MB的图片/PDF/Word文件</div></template></el-upload>
</template>
<script lang="ts" setup>
const props = defineProps({size: {require: false,type: Number,default: 200}
})
const message = useMessage() // 消息弹窗
// 暴露出success接口上传成功返回,setUpload:上传文件操作返回true,删除返回false
const emit = defineEmits(['success', 'setUpload'])
const formLoading = ref(false) // 表单的加载中
const fileList = ref([]) // 文件列表
const uploadRef = ref()
const fileTypes = '.jpeg, .jpg, .png, .pdf, .doc, .docx'
/** 处理上传的文件发生变化 */
const handleChange = (file) => {const fileName = file.nameconst fileType = fileName.substring(fileName.lastIndexOf('.'))if (fileTypes.indexOf(fileType) === -1) {message.warning('上传的文件不符合所需的格式!')fileList.value.splice(-1)return}const maxSize = props.sizeconst size = maxSize * 1024 * 1024if (file.size > size) {unref(uploadRef)?.clearFiles()message.warning('上传文件大小不超过' + props.size + 'MB')return}if (file.status === 'ready') {emit('setUpload', true)}
}
const hanldeRemove = () => {emit('setUpload', false)
}
/** 文件数超出提示 */
const handleExceed = (): void => {message.error('最多只能上传1份文件!')
}
// 外部调用才一并上传文件接口请求
const submitFun = () => {if (!fileList.value.length) returnreturn new Promise(async (resolve) => {let formData = new FormData()fileList.value.map((item: any) => {formData.append('file', item.raw)})// 可直接 resolve(formData),外部调用接口let res = await xxxformLoading.value = falseif (res.data) resolve(res.data)else message.warning('文件上传失败')})
}
defineExpose({ submitFun })
</script>
<style lang="scss" scoped>
:deep(.el-upload-list__item-info) {max-width: 350px;
}
</style>

取消自动上传

针对多个文件上传,利用submitFormSuccess返回多个后,拼接成字符串返回
setUpload 是针对外部调用时监听到上传文件操作(未调用接口的),取消表单校验验操作
针对校验问题写了很多,后续再优化

<template><el-uploadref="uploadRef"v-model:file-list="showList":action="url":auto-upload="false":disabled="formLoading":headers="uploadHeaders":limit="props.limit":on-change="handleChange":on-remove="hanldeRemove":on-error="submitFormError":on-exceed="handleExceed":on-success="submitFormSuccess"accept=".jpg, .png, .jpeg"><template #trigger><el-button type="primary">上传图片</el-button></template><template #tip><div class="el-upload__tip text-red">请上传大小不超过{{ props.size }}MB的图片,最多上传{{ props.limit }}张</div></template></el-upload>
</template>
<script lang="ts" setup>
import { getAccessToken, getTenantId } from '@/utils/auth'
const props = defineProps({size: {require: false,type: Number,default: 20},limit: {require: false,type: Number,default: 1}
})
const url = import.meta.env.VITE_UPLOAD_URL
const message = useMessage() // 消息弹窗
const emit = defineEmits(['success', 'setUpload'])
const uploadHeaders = ref() // 上传 Header 头
const formLoading = ref(false) // 表单的加载中
const fileList = ref([]) // 文件列表
const showList = ref([]) // 文件列表
const uploadRef = ref()
const imgTypes = ['image/jpeg', 'image/png', 'image/jpg']
/** 处理上传的文件发生变化 */
const handleChange = (file, files) => {if (imgTypes.indexOf(file.raw.type) === -1) {message.warning('上传的文件不符合所需的格式!')showList.value.splice(-1)return}const maxSize = props.sizeconst size = maxSize * 1024 * 1024if (file.size > size) {unref(uploadRef)?.clearFiles()message.warning('上传文件大小不超过' + props.size + 'MB')return}if (file.status === 'ready') {fileList.value = filesemit('setUpload', true)}
}
// @ts-ignore文件移除
const hanldeRemove = (file, files) => {fileList.value = filesif (files.length) emit('setUpload', false)
}
/** 文件数超出提示 */
const handleExceed = (): void => {message.error('最多只能上传' + props.limit + '份文件!')
}
/** 上传错误提示 */
const submitFormError = (): void => {unref(uploadRef)?.clearFiles()message.error('文件上传失败,请您重新上传!')
}
/** 文件上传成功处理 */
const fileNum = ref(0)
// @ts-ignore
const submitFormSuccess = (val, file, files) => {fileNum.value++if (fileNum.value === files.length) {let ids = [] as anyfiles.map((item: any) => {ids.push(item.response.data)})formLoading.value = falsefileNum.value = 0fileList.value = []emit('success', ids.join(','))}
}
// 说明 在文件上传处理fileList.value为[],故再次调用时不会执行改方法
// 外部调用
const submitFun = () => {if (!fileList.value.length) returnreturn new Promise(() => {// 提交请求uploadHeaders.value = {Authorization: 'Bearer ' + getAccessToken(),'tenant-id': getTenantId()}unref(uploadRef)?.submit()})
}
defineExpose({ submitFun })
</script>
<style lang="scss" scoped>
:deep(.el-upload-list__item-info) {max-width: 300px;
}
</style>

调用案例

<el-form-item label="相关文件" prop="url"><upload ref="uploadRef" @success="getFileUrl" @set-upload="setUpload" />
</el-form-item>
// 上传图片
const getFileUrl = (url) => {formData.value.url= urlsubmitForm()
}
// 表单校验
const setUpload = (bol) => {if (bol) {formData.value.url= ''unref(formRef).clearValidate('url')} else {unref(formRef).validateField('url')}
}
// 表单提交按钮
const submitForm = async () => {await uploadRef.value.submitFun()await formRef.value.validate()//表单校验成功,和表单参数一起提交
}

文章转载自:

http://fX2CY3z2.zpdjh.cn
http://pSXbbXvx.zpdjh.cn
http://QBR8ppmO.zpdjh.cn
http://lPHLLeHH.zpdjh.cn
http://2oXM4Dn9.zpdjh.cn
http://vs2P3Pzw.zpdjh.cn
http://fznyZJth.zpdjh.cn
http://uLeydJ1m.zpdjh.cn
http://bmA8lgnm.zpdjh.cn
http://09zQ12PW.zpdjh.cn
http://kMlglVvO.zpdjh.cn
http://7B3sNQbi.zpdjh.cn
http://eDLhKHqf.zpdjh.cn
http://I60yFHVU.zpdjh.cn
http://G0oc5V10.zpdjh.cn
http://yJbk873W.zpdjh.cn
http://291LcW6x.zpdjh.cn
http://g4IKtHuJ.zpdjh.cn
http://NbuilUwb.zpdjh.cn
http://EfkClBTv.zpdjh.cn
http://F2dL7OpM.zpdjh.cn
http://hu9CI0AM.zpdjh.cn
http://aI3ksiC0.zpdjh.cn
http://Beo22LMO.zpdjh.cn
http://1moe1FB8.zpdjh.cn
http://1y1l67bO.zpdjh.cn
http://SWDalnm6.zpdjh.cn
http://JJHG4dl3.zpdjh.cn
http://OHbjCrSN.zpdjh.cn
http://V6RW5yJy.zpdjh.cn
http://www.dtcms.com/a/386766.html

相关文章:

  • 只有select权限,确实也可以for update锁表
  • HBase核心知识点总结
  • Springboot 使用缓存cache
  • 基于边缘计算的智能管控终端充电站有序充电系统设计与实现 —— 面向实时功率调度需求
  • Nordic BLE智能门锁应用
  • IDEA 连接MySQL数据导出和导入指南
  • 在window下使用visual studio + cmake gui 源码编译 gRPC
  • C# halcon 拼图例子
  • 网络:常见的高速网卡(100Gbps和400Gbps)
  • 第十四届蓝桥杯青少组C++选拔赛[2022.12.18]第二部分编程题(4、充电站)
  • 华为P10plus adb 无线调试USB拔除后立即失效解决
  • openharmony 鸿蒙 下 利用蓝牙API(a2dp模块-高级音频,ble模块-低功耗蓝牙等)完成对蓝牙音响的控制(蓝牙广播)
  • 软考-系统架构设计师 需求工程详细讲解
  • 优化 Coze Studio 依赖管理:镜像源配置与高效实践
  • AIGC入门,从理解通信协议sse与streamhttp开始
  • cuda编程笔记(20)-- 混合精度计算
  • 服务器性能测试的性能指标包括哪些?服务器性能测试工具有哪些?
  • 【面试场景题】跨库数据表关联查询怎么处理
  • 无需复杂正则:SLS 新脱敏函数让隐私保护更简单高效
  • [特殊字符]网络安全学习笔记day1——基本概念,包括域名、DNS、脚本语言、后门、WEB、WEB漏洞
  • 使用ZYNQ芯片和LVGL框架实现用户高刷新UI设计系列教程(第三十讲)
  • Langchain4j开发之AI Service
  • 红帽证书需要什么报考条件
  • Ubuntu 虚拟机 | DPDK 协议栈开发 | 2、DPDK驱动绑定VMWare模拟网卡 + Testpmd发包测试
  • 【高等数学】第十二章 无穷级数——第二节 常数项级数的审敛法
  • 从弱 AI 到通用人工智能(AGI):我们还需要跨越哪些技术鸿沟?
  • Redis 在分布式会话管理中的应用:从单体到微服务的平滑迁移
  • 说说你对闭包的理解? 闭包使⽤场景
  • MySQL 存储过程完整实战手册---一篇吃透 Stored Procedure
  • Leetcode 763. 划分字母区间 贪心