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

uniapp3.0实现图片上传公用组件上传uni-file-picker,uni.uploadFile

用uniapp3.0的写法组合式api,setup形式封装一个图片上传公用组件,要求

1、使用uni-file-picker选择文件

2、uni.uploadFile上传图片

3、要能支持上传接口动态化

4、支持删除如片列表中已上传项

5、可以预览已上传列表图片

6、支持动态化限制图片格式,图片大小,

7、上传成功后走公用组件返回图片列表list,

具体的封装代码,和在页面使用该组件的例子

组件ImageUploader.vue

<template><view class="image-uploader"><view class="header"><text>图片上传</text><text>{{ uploadedFiles.length }}/{{ maxCount }}</text></view><uni-file-picker multiple :limit="maxCount" :disable="uploadedFiles.length >= maxCount" @select="onFileChange":ext-class="filePickerClass" :file-extname="allowedFormats" @delete="removeImage"><view class="upload-btn"><uni-icons type="camera-filled" color="#007aff" size="40"></uni-icons></view></uni-file-picker></view>
</template><script setup>let base = import.meta.env.VITE_APP_BASE_APIlet token = uni.getStorageSync(ACCESS_TOKEN)const props = defineProps({maxCount: {type: Number,default: 1},uploadUrl: {type: String,default: '/ap/files/upload555'//自己的上传地址},allowedFormats: {type: Array,default: () => ['jpg', 'jpeg', 'png', 'gif']},maxSize: {type: Number,default: 5 * 1024 * 1024 // 5MB},value: {type: Array,default: () => {return [];},},})const emit = defineEmits(['update:list'])const uploadedFiles = computed({get: () => {return props.value;},set: (val) => {emit('update:value', val);},});const onFileChange = async (files) => {console.log('files', files)// const files = event.detail.tempFilesconst filelist = files.tempFiles; // 获取选中的文件for (const file of filelist) {if (!props.allowedFormats.includes(file.name.split('.').pop().toLowerCase())) {uni.showToast({title: '不支持的文件格式',icon: 'none'})continue}if (file.size > props.maxSize) {uni.showToast({title: '文件大小超出限制',icon: 'none'})continue}console.log('hsjhj')uni.uploadFile({url: base + props.uploadUrl,filePath: file.path,name: 'file', // 这里根据API的要求来定义header: {// 'Content-Type': 'multipart/form-data', // 设置上传文件的 Content-Type'Authorization': `Bearer ${token}`, // 自定义头部信息,比如 Authorization'Tenant-Id': 1,'CLIENT-TOC': 'Y'},success: (uploadFileRes) => {console.log('upload success:', uploadFileRes);let data = JSON.parse(uploadFileRes.data)console.log('upload success: data', data);if (data && data.code == 0) {uploadedFiles.value.push({url: data.data.url})console.log('uploadedFiles.value', uploadedFiles.value.length);emit('update:list', uploadedFiles.value)} else {tip.error('上传失败')}},fail: (error) => {console.error('upload fail:', error);tip.error('上传失败')// 处理上传失败的逻辑}});}}const previewImage = (url) => {uni.previewImage({urls: uploadedFiles.value.map(file => file.url),current: url})}const removeImage = (file) => {console.log('hhj', file)uploadedFiles.value.splice(file.index, 1)emit('update:list', uploadedFiles.value)}const filePickerClass = {'file-picker': true,'disabled': uploadedFiles.value.length >= props.maxCount}
</script><style scoped>.image-uploader {padding: 16px;background-color: #fff;border-radius: 8px;box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);}.header {display: flex;justify-content: space-between;margin-bottom: 8px;}.upload-btn {display: flex;align-items: center;justify-content: center;width: 80px;height: 80px;border: 2px dashed #ddd;border-radius: 8px;color: #bbb;}
</style>

页面使用,预留了上传成功后的回调方法,可不传,也可以直接v-model绑定
 

      <imageUploader :max-count="4" @update:list="updateImageList" v-model:value="imageList"/>const imageList = ref([])const updateImageList = (list) => {console.log('imageList444',imageList)// imageList.value = list ,//可以赋值也可以做其他操作}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • Mac电脑装不了软件怎么办 苹果电脑软件安装失败解决办法 安装macos空间不足
  • 【开源社区】Elasticsearch(ES)中空值字段 null_value 及通过exists查找非空文档
  • 【MySQL】全面剖析索引失效、回表查询与索引下推
  • 【开端】web系统中返回状态码组织管理
  • 回顾Python
  • 在树莓派上安装udhcpd的步骤
  • 2024年TI杯E题-三子棋游戏装置方案分享-jdk123团队-第三弹视觉模块的封装
  • 打造核心竞争力:中集集团技术创新之路
  • 【MetaGPT系列】【MetaGPT完全实践宝典——多智能体实践(辩论赛)构建】
  • 十九、虚拟机VMware Workstation(CentOSDebian)的安装
  • 前端项目中的Server-sent Events(SSE)项目实践及其与websocket的区别
  • PDF怎么在线转Word?介绍四种转换方案
  • MATLAB(R和C++)大肠杆菌合成生物机械数学模型
  • c语言中的volatile(从系统层面看)
  • 计算机网络408考研 2019
  • Computed property XXX was assigned to but it has no setter
  • django开发-定时任务的使用
  • Hibernate【inverse和cascade属性】知识要点
  • JavaSE小实践1:Java爬取斗图网站的所有表情包
  • Java读取Properties文件的六种方法
  • js正则,这点儿就够用了
  • learning koa2.x
  • mysql_config not found
  • Rancher-k8s加速安装文档
  • uni-app项目数字滚动
  • vue脚手架vue-cli
  • Vue全家桶实现一个Web App
  • 区块链将重新定义世界
  • 日剧·日综资源集合(建议收藏)
  • 使用SAX解析XML
  • 使用阿里云发布分布式网站,开发时候应该注意什么?
  • 看到一个关于网页设计的文章分享过来!大家看看!
  • Semaphore
  • Spark2.4.0源码分析之WorldCount 默认shuffling并行度为200(九) ...
  • 不要一棍子打翻所有黑盒模型,其实可以让它们发挥作用 ...
  • 哈罗单车融资几十亿元,蚂蚁金服与春华资本加持 ...
  • 数据可视化之下发图实践
  • ​LeetCode解法汇总1410. HTML 实体解析器
  • #if 1...#endif
  • #NOIP 2014#day.2 T1 无限网络发射器选址
  • #我与Java虚拟机的故事#连载11: JVM学习之路
  • #周末课堂# 【Linux + JVM + Mysql高级性能优化班】(火热报名中~~~)
  • (145)光线追踪距离场柔和阴影
  • (C语言)球球大作战
  • (Java入门)抽象类,接口,内部类
  • (MTK)java文件添加简单接口并配置相应的SELinux avc 权限笔记2
  • (搬运以学习)flask 上下文的实现
  • (差分)胡桃爱原石
  • (二)windows配置JDK环境
  • (非本人原创)我们工作到底是为了什么?​——HP大中华区总裁孙振耀退休感言(r4笔记第60天)...
  • (附源码)spring boot北京冬奥会志愿者报名系统 毕业设计 150947
  • (附源码)计算机毕业设计ssm电影分享网站
  • (力扣)1314.矩阵区域和
  • (转)JVM内存分配 -Xms128m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=512m
  • (转)memcache、redis缓存