UniApp基于xe-upload实现文件上传组件

xe-upload地址:文件选择、文件上传组件(图片,视频,文件等) - DCloud 插件市场

致敬开发者!!!

感觉好用的话,给xe-upload的作者一个好评

背景:开发中经常会有上传附件的情况,但是找了一圈没有满意的组件,无意间看到xe-upload,满足我需要上传图片和视频的需求,直接使用示例项目开始二次开发my-file-upload。

修改内容:

1.文件的点击事件

2.对video类型文件的处理

3.根据文件名称创建file文件内容

<template><view><view class="upload-wrap"><view class="cu-form-group1"><view class="label">{{label}}:</view><view class="btn-click mgb-16 upload-btn" @click="handleUploadClick" v-show="!disabled"><image :src="icons.upload" mode="aspectFill" class="upload-icon" /><text class="upload-text">上传{{ label }}</text></view></view><view class="mgb-16 file-wrap" v-for="(item, index) in fileList" :key="index"><view class="btn-click file-line" @click="handlePreview(item)"><!-- <view class="btn-click file-line" @click="handleUploadFile(item)"> --><view class="file-info"><image :src="icons[item.fileType || 'file']" mode="aspectFill" class="file-icon" /><text class="file-name">{{ item.name || title[type] }}</text></view><image :src="icons.close" mode="aspectFill" class="file-icon"@click.stop="handleDeleteFile(index)" /></view></view><view class="mgb-16 file-wrap" v-if="fileList.length === 0 && disabled"><view class="file-line"><text class="file-empty">暂无数据</text></view></view><view><video id="myVideo" :src="videoUrl" autoplay loop muted objectFit="cover" v-if="showVideo"></video></view></view><xe-upload ref="XeUpload" :options="uploadOptions" @callback="handleUploadCallback"></xe-upload></view>
</template><script>export default {name: 'MyFileUpload',components: {},props: {type: {default: 'image', // image, video, filetype: String,},list: {default: () => ([]),type: Array,},// disabled: {// 	default: false,// 	type: Boolean,// },value: {type: String, // 或者是 File[],取决于你的需求default: null},maxFile: {type: Number, //最大上传数量default: 1},label: {type: String, // 或者是 File[],取决于你的需求default: '附件'},},data() {return {// uploadOptions 参数跟uni.uploadFile的参数是一样的(除了类型为Function的属性)uploadOptions: {// url: 'http://192.168.31.185:3000/api/upload', // 不传入上传地址则返回本地链接},uploadUrl: "/sys/common/upload",staticUrl: "/sys/common/static/",fileList: [],title: {image: '图片',video: '视频',file: '文件',},icons: {upload: '/static/xeUpload/icon_upload.png',close: '/static/xeUpload/icon_close.png',image: '/static/xeUpload/icon_image.png',video: '/static/xeUpload/icon_video.png',file: '/static/xeUpload/icon_file.png',},disabled: false,showVideo: false,videoUrl: ''};},watch: {value: {async handler(val) {if (val && val !== null && val !== undefined) {const url = this.$config.apiUrl + this.staticUrl + val;const file = this.urlToFile(url);this.fileList = [file];if (this.fileList.length === this.maxFile) {this.disabled = true;}}},immediate: true,deep: true,},},onLoad: function() {this.videoContext = uni.createVideoContext('myVideo', this)},methods: {handleUploadClick() {// 使用默认配置则不需要传入第二个参数// App、H5 文件拓展名过滤 { extension: ['.doc', '.docx'] } 或者 { extension: '.doc, .docx' }this.$refs.XeUpload.upload(this.type);// 可以根据当前的平台,传入选择文件的参数,例如// 注意 当chooseMedia可用时,会优先使用chooseMedia// // uni.chooseImage// this.$refs.XeUpload.upload(type, {// 	count: 6,// 	sizeType: ['original', 'compressed'],// 	sourceType: ['album'],// });// // uni.chooseVideo// this.$refs.XeUpload.upload(type, {// 	sourceType: ['camera', 'album'],// });// // uni.chooseMedia (微信小程序2.10.0+;抖音小程序、飞书小程序;京东小程序支持)// this.$refs.XeUpload.upload(type, {// 	count: 9,// 	sourceType: ['album', 'camera'],// });},handleUploadCallback(e) {console.log('UploadCallback', e);if (['choose', 'success'].includes(e.type)) {// 根据接口返回修改对应的response相关的逻辑const tmpFiles = (e.data || []).map(({response,tempFilePath,name,fileType}) => {// 当前测试服务返回的数据结构如下// {//   "result": {//       "fileName": "fileName",//       "filePath": `http://192.168.1.121:3000/static/xxxxx.png`,//   },//   "success": true,// }const res = response?.result || {};const tmpUrl = res.filePath ?? tempFilePath;const tmpName = res.fileName ?? name;return {...res,url: tmpUrl,name: tmpName,fileType,};});this.fileList.push(...tmpFiles);this.handleUploadFile(e.data[0].tempFilePath);}},// 自定义上传handleUploadFile(url) {var that = this;console.log('UploadFile', url);if (url != undefined) {that.$http.upload(that.$config.apiUrl + that.uploadUrl + '?biz=temp', {filePath: url,name: 'file',}).then(res => {console.log('handleUpload success', res);//回传至表单that.$emit('input', res.data.message);const tmpData = JSON.parse(res.data);uni.showToast({title: tmpData.success ? '上传成功' : '上传失败',icon: 'none'});})}},// 预览handlePreview(item) {console.log('PreviewFile', item);const fileType = this.getFileType(item.name);const url = item.url;if (fileType === 'image') {return uni.previewImage({current: url,urls: [url],});}else if (fileType === 'video') {this.videoUrl = url;this.showVideo = !this.showVideo;//全屏显示// this.videoContext.requestFullScreen();}// #ifndef H5else if (fileType === 'office') {return uni.openDocument({filePath: url,fail: (err) => {console.log(err);uni.showToast({icon: 'none',title: '文件预览失败'});},});}// #endifelse{uni.showModal({title: '提示',content: url,showCancel: false,});}},handleDeleteFile(index) {this.fileList.splice(index, 1);if (this.fileList.length < this.maxFile) {this.disabled = false;}},urlToFile(url) {// 获取URL的最后一部分const lastPart = url.split('/').pop();// 获取文件名(不包括扩展名)const filenameWithoutExtension = lastPart.split('_').slice(0, -1).join('_');// 获取文件扩展名const extension = lastPart.split('.').pop();// 组合文件名和扩展名const filename = filenameWithoutExtension + '.' + extension;const fileType = this.getFileType(url);const file = {"fileName": filename,"fileKey": lastPart,"filePath": url,"url": url,"name": filename,"fileType": fileType}return file;},/*** 获取文件类型* @param {String} fileName 文件链接* @returns {String} fileType => '', image, video, audio, office, unknown*/getFileType(fileName = '') {const fileType = fileName.split('.').pop();// let suffix = flieArr[flieArr.length - 1];// if (!suffix) return '';// suffix = suffix.toLocaleLowerCase();const image = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp'];if (image.includes(fileType)) return 'image';const video = ['mp4', 'm4v'];if (video.includes(fileType)) return 'video';const audio = ['mp3', 'm4a', 'wav', 'aac'];if (audio.includes(fileType)) return 'audio';const office = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'plain'];if (office.includes(fileType)) return 'office';return 'unknown';},},};
</script><style lang="scss" scoped>view {box-sizing: border-box;}.label{text-align: justify;padding-right: 15px;white-space: nowrap;font-size: 15px;position: relative;height: 30px;line-height: 30px;}.cu-form-group1 {background-color: #ffffff;padding: 1px 15px 1px 0px;display: flex;align-items: center;min-height: 50px;// justify-content: space-between;}.btn-click {transition: all 0.3s;opacity: 1;}.btn-click:active {opacity: 0.5;}.mgb-16 {margin-bottom: 16rpx;&:last-child {margin-bottom: 0;}}.upload-wrap {width: 100%;border-radius: 16rpx;background: white;padding: 32rpx;.upload-btn {width: 60%;height: 120rpx;border: 2rpx dashed #AAAAAA;background: #FAFAFA;border-radius: 16rpx;display: flex;align-items: center;justify-content: center;flex-direction: column;.upload-icon {width: 48rpx;height: 48rpx;margin-bottom: 8rpx;}.upload-text {font-size: 26rpx;color: #9E9E9E;line-height: 40rpx;}}.file-wrap {.file-line {width: 100%;background: #F5F5F5;border-radius: 8rpx;padding: 16rpx;font-size: 26rpx;color: #1A1A1A;line-height: 40rpx;display: flex;align-items: center;justify-content: space-between;.file-info {width: 90%;display: flex;align-items: center;.file-name {max-width: 80%;padding-left: 16rpx;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}}.file-icon {width: 40rpx;height: 40rpx;flex-shrink: 0;}.file-empty {color: #999999;}}}}
</style>

父组件中引入使用

<my-file-upload type="file" v-model="model.attachment" label="附件"></my-file-upload>import myFileUpload from '@/components/my-componets/my-file-upload.vue';export default {name: "Test",components:{ myFileUpload },props:{formData:{type:Object,default:()=>{},required:false}},data(){return {model: {},}},onLoad: function (option) {}},created(){},methods:{}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/75677.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

STM32 HAL库之GPIO示例代码

LED灯不断闪烁 GPIO初始化&#xff0c;main文件中的 MX_GPIO_Init(); 也就是在 gpio.c文件中 void MX_GPIO_Init(void) {GPIO_InitTypeDef GPIO_InitStruct {0};/* GPIO Ports Clock Enable */__HAL_RCC_GPIOE_CLK_ENABLE();__HAL_RCC_GPIOC_CLK_ENABLE();__HAL_RCC_GPIOA_C…

二维数点 系列 题解

1.AT_dp_w Intervals 我的博客 2.CF377D Developing Games 我的博客 这两道题是比较经典的线段树区间 trick&#xff0c;希望自己可以在以后的比赛中手切。 3.洛谷 P10814 离线二维数点 题意 给你一个长为 n n n 的序列 a a a&#xff0c;有 m m m 次询问&#xff0c…

vulkanscenegraph显示倾斜模型(5.9)-vsg中vulkan资源的编译

前言 上一章深入剖析了GPU资源内存及其管理&#xff0c;vsg中为了提高设备内存的利用率&#xff0c;同时减少内存(GPU)碎片&#xff0c;采用GPU资源内存池机制(vsg::MemoryBufferPools)管理逻辑缓存(VkBuffer)与物理内存(VkDeviceMemory)。本章将深入vsg中vulkan资源的编译(包含…

探秘 Python 网络编程:构建简单聊天服务器

在计算机网络的世界里&#xff0c;网络编程是实现不同设备之间通信的关键技术。Python 凭借其简洁的语法和强大的库支持&#xff0c;在网络编程领域有着广泛的应用。无论是构建简单的聊天服务器&#xff0c;还是开发复杂的网络应用&#xff0c;Python 都能轻松胜任。 1 理论基础…

Go语言Slice切片底层

Go语言&#xff08;Golang&#xff09;中切片&#xff08;slice&#xff09;的相关知识、包括切片与数组的关系、底层结构、扩容机制、以及切片在函数传递、截取、增删元素、拷贝等操作中的特性。并给出了相关代码示例和一道面试题。关键要点包括&#xff1a; 数组特性&#xf…

vue3 ts 自定义指令 app.directive

在 Vue 3 中&#xff0c;app.directive 是一个全局 API&#xff0c;用于注册或获取全局自定义指令。以下是关于 app.directive 的详细说明和使用方法 app.directive 用于定义全局指令&#xff0c;这些指令可以用于直接操作 DOM 元素。自定义指令在 Vue 3 中非常强大&#xff0…

基于python的机器学习(五)—— 聚类(二)

一、k-medoids聚类算法 k-medoids是一种聚类算法&#xff0c;它是基于k-means聚类算法的一种改进。k-medoids算法也是一种迭代算法&#xff0c;但是它将中心点限定为数据集中的实际样本点&#xff0c;而不是任意的点。 具体来说&#xff0c;k-medoids算法从数据集中选择k个初…

解释:指数加权移动平均(EWMA)

指数加权移动平均&#xff08;EWMA, Exponential Weighted Moving Average&#xff09; 是一种常用于时间序列平滑、异常检测、过程控制等领域的统计方法。相比普通移动平均&#xff0c;它对最近的数据赋予更高权重&#xff0c;对旧数据逐渐“淡化”。 ✅ 一、通俗理解 想象你…

Spring Boot 项目基于责任链模式实现复杂接口的解耦和动态编排!

全文目录&#xff1a; 开篇语前言一、责任链模式概述责任链模式的组成部分&#xff1a; 二、责任链模式的核心优势三、使用责任链模式解耦复杂接口1. 定义 Handler 接口2. 实现具体的 Handler3. 创建订单对象4. 在 Spring Boot 中使用责任链模式5. 配置责任链6. 客户端调用 四、…

COMSOL仿真遇到的两个小问题

最近跑热仿真的时候跑出了两个问题&#xff0c;上网查发现也没什么解决方式&#xff0c;最后自己误打误撞的摸索着解决了&#xff0c;在这里分享一下。 问题一 我当时一准备跑仿真就弹出了这个东西&#xff0c;但在此之前从未遇到 然后我试着在它说的路径中建立recoveries文件…

如何在英文学术写作中正确使用标点符号?

标点符号看似微不足道&#xff0c;但它们是书面语言的无名英雄。就像熟练的指挥家指挥管弦乐队一样&#xff0c;标点符号可以确保您的写作流畅、传达正确的含义并引起读者的共鸣。正如放错位置的音符会在音乐中造成不和谐一样&#xff0c;放错位置的逗号或缺少分号也会使您的写…

【深度学习与大模型基础】第10章-期望、方差和协方差

一、期望 ——————————————————————————————————————————— 1. 期望是什么&#xff1f; 期望&#xff08;Expectation&#xff09;可以理解为“长期的平均值”。比如&#xff1a; 掷骰子&#xff1a;一个6面骰子的点数是1~6&#x…

JAVA虚拟机(JVM)学习

入门 什么是JVM JVM&#xff1a;Java Virtual Machine&#xff0c;Java虚拟机。 JVM是JRE(Java Runtime Environment)的一部分&#xff0c;安装了JRE就相当于安装了JVM&#xff0c;就可以运行Java程序了。JVM的作用&#xff1a;加载并执行Java字节码&#xff08;.class&#…

【数据结构与算法】——堆(补充)

前言 上一篇文章讲解了堆的概念和堆排序&#xff0c;本文是对堆的内容补充 主要包括&#xff1a;堆排序的时间复杂度、TOP 这里写目录标题 前言正文堆排序的时间复杂度TOP-K 正文 堆排序的时间复杂度 前文提到&#xff0c;利用堆的思想完成的堆排序的代码如下&#xff08;包…

什么是柜台债

柜台债&#xff08;柜台债券业务&#xff09;是指通过银行等金融机构的营业网点或电子渠道&#xff0c;为投资者提供债券买卖、托管、结算等服务的业务模式。它允许个人、企业及机构投资者直接参与银行间债券市场的交易&#xff0c;打破了以往仅限机构参与的壁垒。以下是综合多…

【Android读书笔记】读书笔记记录

文章目录 一. Android开发艺术探索1. Activity的生命周期和启动模式1.1 生命周期全面分析 一. Android开发艺术探索 1. Activity的生命周期和启动模式 1.1 生命周期全面分析 onPause和onStop onPause后会快速调用onStop&#xff0c;极端条件下直接调用onResume 当用户打开新…

Java对象内存结构详解

Java对象内存结构详解 Java对象在JVM内存中的存储结构可以分为三个部分&#xff1a;对象头&#xff08;Header&#xff09;、实例数据&#xff08;Instance Data&#xff09;和对齐填充&#xff08;Padding&#xff09;。以下是64位JVM&#xff08;开启压缩指针&#xff09;下…

【TI MSPM0】Printf重定向学习

一、新建工程 通过XDS110与电脑进行通信。 选择这两个引脚 需要添加这两个头文件 在程序中添加这三个函数即可对printf进行重定向 二、封装函数 另一种方法 封装一个函数&#xff0c;定义一个数组

深度强化学习基础 0:通用学习方法

过去自己学习深度强化学习的痛点&#xff1a; 只能看到各种术语、数学公式勉强看懂&#xff0c;没有建立清晰且准确关联 多变量交互关系浮于表面&#xff0c;有时候连环境、代理控制的变量都混淆 模型种类繁多&#xff0c;概念繁杂难整合、对比或复用&#xff0c;无框架分析所…

asm汇编源代码之-字库转换程序

将标准的16x16点阵汉字库(下载16x16汉字库)转换成适合VGA文本模式下显示的点阵汉字库 本程序需要调用file.asm中的子程序,所以连接时需要把file连接进来,如下 C:\> tlink chghzk file 调用参数描述如下 C:\> chghzk ; 无调用参数,转换标准库文件(SRC16.FNT)为适合VGA…