【vue/uniapp】使用 uni.chooseImage 和 uni.uploadFile 实现图片上传(包含样式,可以解决手机上无法上传的问题)

引入:
之前写过一篇关于 uview 1.x 版本上传照片 的文章,但是发现如果是在微信小程序的项目中嵌入 h5 的模块,这个 h5 的项目使用 u-upload 的话,图片上传功能在电脑上正常,但是在手机的小程序上测试就不会生效,点击上传加号按钮毫无反应。
解决方法:
现在最终的解决方法是,使用 uniapp 的 uni.chooseImage 来选择照片,使用 uni.uploadFile 来上传图片,其他所有的样式和逻辑都自己来实现,最终的效果长这样:

代码与解析:
单独写一个组件,先实现样式:

<template><view class="meeting-image"><view class="title"><text></text><!-- 展示图片张数 --><text style="color: #a1a1a1;">({{ list.length }}/9)</text></view><view class="img_wrap flex-row flex-justify-between"><view class="img_box" v-for="(item, index) in list" :key="index"><!-- 展示上传之后的图片 --><image :src="item.imgUrl" class="pic" mode="aspectFill" @click="previewImage(index)" /><!-- 删除图标 --><!-- 这里的删除图标叉叉是用的在线网址,$public 是挂载在原型上的,可以自定义 --><image :src="`${$public()}/project-meeting/icon_20_close.png`" class="close"@click.stop="handleDeleteImg(index, item)" /></view><!-- 上传的方框 --><view class="upload-box" @click="chooseImg" v-if="list.length !== 9 && isSponsorUserFlag == 1"></view></view><u-toast ref="uToast" /></view>
</template>
.meeting-image {.title {font-size: 32rpx;line-height: 40 rpx;text:nth-of-type(1) {color: #ff3f30;padding-right: 4rpx;}text:nth-of-type(3) {padding-left: 12rpx;color: #cccccc;}}.img_wrap {flex-wrap: wrap;&::after {width: calc((100% - 40rpx) / 3);display: block;content: '';}.img_box {margin-top: 20rpx;position: relative;width: calc((100% - 40rpx) / 3);height: 220rpx;.pic {width: 100%;height: 100%;object-fit: cover;border-radius: 14rpx;}.close {position: absolute;top: -8rpx;right: -8rpx;width: 40rpx;height: 40rpx;}}.upload-box {position: relative;width: calc((100% - 40rpx) / 3);height: 220rpx;border: 1px solid #e5e5e5;box-sizing: border-box;position: relative;border-radius: 14rpx;margin-top: 20rpx;&::after {display: block;content: '';width: 1px;height: 96rpx;background-color: #e5e5e5;position: absolute;left: 105rpx;top: 50rpx;}&::before {display: block;content: '';width: 96rpx;height: 1px;background-color: #e5e5e5;position: absolute;right: 60rpx;top: 100rpx;}}}
}

js 逻辑部分,我这里后端提供的 api 有上传(查询文件地址),即代码中的 previewUrl ,删除的实现方法是在本地进行的,是对数组进行 splice 之后,再将最新的图片数组保存进大数组一次,最后再进行上传,注释写的很详细,方便以后回顾查看。

简单解释:

chooseImg 是最先执行的函数,即点击上传按钮时执行,进来判断是不是数量超过了 9 张,没超过就往下走;
使用 uni.chooseImage 进行图片选择功能,配置相应参数和值,选择成功,走到 then 的成功回调里,回显照片,此时调接口 previewUrl 来上传获取图片id;
然后将图片保存进数组中

<script>
import { BASE_URL } from '@/pages/workTable/utils/constant'
import { previewUrl } from '@/pages/workTable/utils/api.js'export default {name: 'meeting-image',// 接收参数props: {fileList: {type: Array,default: []},// 用于该页面有很多项,而每一项都需要传一组图片的页面subItem: {},// 用于只传一组图片的页面picListArr: {},picList: {}},data() {return {list: [],count: 9,}},computed: {},methods: {// 预览功能暂时有问题previewImage(index) {console.log('预览', this.list.map(el => el.imgUrl));uni.previewImage({current: index,urls: this.list.map(el => el.imgUrl)})},// 点击上传按钮触发chooseImg() {// 如果大于 9 张就不触发底下的 uni.chooseImageif (this.count == 0) {this.$refs.uToast.show({title: '最多能上传9张照片',duration: 2000})return}uni.chooseImage({// 最多可以选择的图片张数,默认9count: this.count,// original 原图,compressed 压缩图,默认二者都有sizeType: ['original', 'compressed'],// album 从相册选图,camera 使用相机,默认二者都有sourceType: ['album', 'camera'],success: res => {// console.log('res',res);uni.showLoading({title: '上传中'})Promise.all(res.tempFilePaths.map(item => {return this.uploadFile({filePath: item})})).then(re => {uni.hideLoading()// let fileList = []re.map((el, index) => {let data = JSON.parse(el.data)// 用于上传成功后照片回显// console.log('data',data.data);previewUrl(data.data).then(res => {console.log('我要预览图片', res); this.list.push({ fileUrl: data.data, imgUrl: res.data })setTimeout(() => {console.log('this.list', this.list);this.saveFile(this.list)}, 800)})})}).catch(err => {console.log('err', err);this.$refs.uToast.show({title: '上传失败',duration: 2000})uni.hideLoading()})},fail: () => { }})},// 上传图片uploadFile({ filePath }) {return new Promise((resolve, reject) => {uni.uploadFile({url: `${BASE_URL}/mobilemanage/api/common/upload?typeEnum=IMAGE`,filePath: filePath,name: 'file',header: {'site3-f-ue': uni.getStorageSync('site3-f-ue')},formData: {typeEnum: "IMAGE",},success: res => {console.log('调用上传接口的结果', res);resolve(res)},fail: error => {reject(error)}})})},// 将图片保存进数组saveFile(list) {console.log('aaaaaaaaaa', list);// 子组件拿接到的父组件传过来的值,subItem 是每一项的数据,里面有 picList 和 picListArrconsole.log('父组件传过来的subItem', this.subItem);// 每一项都需要上传照片这种情况才需要用到 subItemif (this.subItem) {console.log('有 subItem 的情况');let subItem = this.subItemsubItem.picList = []subItem.picListArr = []list.map(async item => {console.log('bbbbbbbb', item);subItem.picList.push({fileUrl: item.fileUrl})console.log('subItem.picList', subItem.picList);})console.log('subItem.picList', subItem.picList);subItem.picList.map(item => {subItem.picListArr.push(item.fileUrl)})console.log('subItem.picListArr', subItem.picListArr);} else {console.log('没有subItem的情况', list);// 只需要上传一组图片let picList = this.picListlet picListArr = this.picListArrpicList = []picListArr = []// console.log('list',list);list.map(async item => {console.log('qqqqqqqqqqqq', item);picList.push({fileUrl: item.fileUrl})})this.$emit('getPicList', picList)console.log('照片列表', picList);}},// 删除图片handleDeleteImg(index, item) {this.list.splice(index, 1)this.saveFile(this.list)this.$refs.uToast.show({title: '删除成功',duration: 2000})}},watch: {// 监视当前图片数组长度,增减张数显示fileList: {handler: function (value) {this.list = valuethis.count = 9 - this.list.length},deep: true,immediate: true}}
}
</script>

使用的时候,父组件进行调用传值:

import uploadImage from '../components/upload-image'
components: {uploadImage
},
<upload-image :fileList="subItem.picList" :subItem="subItem" :projectMeetingId="1":isSponsorUserFlag="1"
></upload-image>

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

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

相关文章

Dependency Dialogue Acts — Annotation Scheme and Case Study [论文解读]

原文链接&#xff1a;https://arxiv.org/pdf/2302.12944.pdf 摘要 在本文中&#xff0c;我们介绍了依存对话行为(Dependency Dialog Act, DDA)&#xff0c;这是一个新颖的框架&#xff0c;旨在捕捉多方对话中说话者意图的结构。DDA结合并适应了现有对话标注框架的特点&#x…

vue保姆级教程----深入了解 Vue3路由守卫

&#x1f4e2; 鸿蒙专栏&#xff1a;想学鸿蒙的&#xff0c;冲 &#x1f4e2; C语言专栏&#xff1a;想学C语言的&#xff0c;冲 &#x1f4e2; VUE专栏&#xff1a;想学VUE的&#xff0c;冲这里 &#x1f4e2; CSS专栏&#xff1a;想学CSS的&#xff0c;冲这里 &#x1f4…

Android Jetpack学习系列——Navigation

写在前面 Google在2018年就推出了Jetpack组件库&#xff0c;但是直到今天我才给重视起来&#xff0c;这真的不得不说是一件让人遗憾的事。过去几年的空闲时间里&#xff0c;我一直在尝试做一套自己的组件库&#xff0c;帮助自己快速开发&#xff0c;虽然也听说过Jetpack&#…

OpenVINS学习5——VioManager.cpp/h学习与注释

前言 之前又看到说VioManager.cpp/h是OpenVINS中的核心程序&#xff0c;这次就看看这里面都写了啥&#xff0c;整体架构什么样&#xff0c;有哪些函数功能。具体介绍&#xff1a; VioManager类 整体分析 VioManager类包含 MSCKF 工作所需的状态和其他算法。我们将测量结果输…

【MongoDB】关于MongoDB更新文档update的操作,十分详细,建议收藏!!!

&#x1f601; 作者简介&#xff1a;一名大四的学生&#xff0c;致力学习前端开发技术 ⭐️个人主页&#xff1a;夜宵饽饽的主页 ❔ 系列专栏&#xff1a;MongoDB数据库学习 &#x1f450;学习格言&#xff1a;成功不是终点&#xff0c;失败也并非末日&#xff0c;最重要的是继…

el-select 多选,选有一个未选择的选项

多选有未选择这个选项后。会出现一个情况&#xff0c;绑定的数据为[‘未选择’,‘cpu1’,‘cpu2’] 进行一个处理&#xff0c;选择&#xff08;未选择&#xff09;就清除&#xff08;其它的选择&#xff09;&#xff0c;选择&#xff08;cpu&#xff09;就清除&#xff08;未选…

Android Studio新手实战——深入学习Activity组件

目录 前言 一、Activity简介 二、任务栈相关概念 三、常用Flag 四、结束当前Activity 五、Intent跳转Activity 六、更多资源 前言 Android是目前全球最流行的移动操作系统之一&#xff0c;而Activity作为Android应用程序的四大组件之一&#xff0c;是Android应用程序的核…

使用valgrind 分析缓存命中

使用valgrind 分析缓存命中 char transpose_submit_desc[] "Transpose submission"; void transpose_submit(int M, int N, int A[N][M], int B[M][N]) { int i,j,tmp;int bsize 8;unsigned long long addrA;unsigned long long addrB;unsigned long long setin…

IO作业4.0

思维导图 创建出三个进程完成两个文件之间拷贝工作&#xff0c;子进程1拷贝前一半内容&#xff0c;子进程2拷贝后一半内容&#xff0c;父进程回收子进程的资源 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <myhead.h> int …

Spring AOP的环境搭建、切入点表达式、通知注解

Spring AOP的实现 Spring AOP环境搭建AOP坐标依赖引入添加xml配置实现三层架构 定义切入点Pointcut("匹配规则")切入点表达式1. 执行所有的公共方法2.执行任意的set方法3.设置指定包下的任意类的任意方法 (指定包: com.svt.service)4.设置指定包及于包下的任意类的任…

手把手教你在Ubuntu22上安装VideoRetalking

VideoReTalking是一种新系统&#xff0c;可以根据输入音频编辑真实世界的谈话头部视频的面孔&#xff0c;即使具有不同的情感&#xff0c;也能生成高质量和口型同步的输出视频。我们的系统将这个目标分解为三个连续的任务&#xff1a; &#xff08;1&#xff09;具有规范表情的…

LCR 176. 判断是否为平衡二叉树

解题思路&#xff1a; class Solution {public boolean isBalanced(TreeNode root) {return recur(root) ! -1;}private int recur(TreeNode root) {if (root null) return 0;int left recur(root.left);if(left -1) return -1;int right recur(root.right);if(right -1) …