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

本文主要是介绍【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>

这篇关于【vue/uniapp】使用 uni.chooseImage 和 uni.uploadFile 实现图片上传(包含样式,可以解决手机上无法上传的问题)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/568454

相关文章

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

C++右移运算符的一个小坑及解决

《C++右移运算符的一个小坑及解决》文章指出右移运算符处理负数时左侧补1导致死循环,与除法行为不同,强调需注意补码机制以正确统计二进制1的个数... 目录我遇到了这么一个www.chinasem.cn函数由此可以看到也很好理解总结我遇到了这么一个函数template<typename T>unsigned

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx