小程序wx.uploadFile异步问题

问题:小程序上传文件后我需要后端返回的一个值,但这个值总是在最后面导致需要这个值的方法总是报错,打印测试后发现这它是异步的。但直接使用 await来等待也不行。 

uploadImg.wxml

<view class="upload-wrap"><view class="list-wrap"><view class="item" wx:for="{{fileList}}" wx:key="index" wx:for-index="index" wx:for-item="item"><image class="file" src="{{item.url}}" data-url="{{item.url}}" bindtap="viewImage"></image><view wx:if="{{!disabled}}" class="icon-delete" data-index="{{index}}" bindtap="delFile"><image class="icon-delete" src="/images/common/icon-delete.png" mode="widthFix"></image></view></view><view wx:if="{{!disabled && fileList.length<maxCount}}" class="add-wrap" bindtap="chooseFile"><image class="icon-camera" src="/images/common/icon-camera.png" mode="widthFix"></image></view></view>
</view>

uploadImg.js

const app = getApp();
Component({properties: {pageFileList: {optionalTypes: [Array, String],value: () => {return []},observer: function (newValue, oldValue) {let list;if (!newValue) {list = [];} else if (typeof newValue == 'string') {list = JSON.parse(newValue);}this.setData({fileList: list})}},disabled: {type: Boolean,default: false},maxSize: {type: Number,value: 5242880, // 5M},maxCount: {type: Number,value: 9,},category: {type: String,value: 'Personal', // 1:Personal,2:Article,3:Meeting},name: {type: String,value: 'Image'},// 文件类型fileType: {type: Number,value: 1, // 1:Image,2:Video,3:Excel,4:PDF文件},},data: {fileList: [],},methods: {// 选择图片chooseFile() {let choseImgCount;let fileListLen = this.data.fileList.length;let maxCount = this.data.maxCount;// 计算每次可上传的文件数量if (fileListLen == maxCount) {choseImgCount = 0;} else if (maxCount - fileListLen > 9) {choseImgCount = 9;} else {choseImgCount = maxCount - fileListLen;}wx.chooseImage({count: choseImgCount,sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有sourceType: ['album', 'camera'], // 选择图片的来源success: (res) => {// 限制最大文件体积let overSizeIndex = res.tempFiles.findIndex(v => v.size > this.data.maxSize);if (overSizeIndex > -1) {let msg = "";if (res.tempFiles.length > 1) {msg = "第" + (overSizeIndex + 1) + "个文件已经超过了最大文件限制:"} else {msg = "该文件已经超过了最大文件限制:"}app.alert.show(msg + (this.data.maxSize / 1024 / 1024).toFixed(0) + "M,请重新上传~");return;}this.uploadFile(res.tempFilePaths);}});},// 上传图片async uploadFile(tempFilePaths) {wx.showLoading({title: '上传中...',mask: true})for (let i = 0; i < tempFilePaths.length; i++) {await this.uploadFileHandler(tempFilePaths, i);if (i == tempFilePaths.length - 1) {this.triggerEvent("uploadFiles", { list: this.data.fileList, name: this.data.name });wx.showToast({title: '上传成功',icon: 'none',duration,})}}},uploadFileHandler(tempFilePaths, i) {let self = this;let fileList = self.data.fileList;return new Promise((resolve, reject) => {wx.uploadFile({url: app.siteinfo.apiUrl + '', // 需要用HTTPS,同时在微信公众平台后台添加服务器地址filePath: tempFilePaths[i], // 上传的文件本地地址name: 'file', // 服务器定义的Key值header: {'content-type': 'multipart/form-data','cookie': wx.getStorageSync('cookie')},formData: {uploadDir: self.data.category,fileType: self.data.fileType,},success: function (res) {wx.hideLoading()if (res.statusCode == 200) {let result = JSON.parse(res.data);if (result.status) {let list = [{ name: self.data.name, url: result.data.fileurl }];fileList = fileList.concat(list);self.setData({ fileList });resolve();} else {app.alert.show(result.errmsg, reject(result.errmsg));}} else {app.alert.show('状态:' + res.statusCode + ',提示:' + res.errMsg, reject(res.errMsg));}},fail: function (err) {wx.hideLoading()app.alert.show(err.errMsg, reject(err.errMsg));}});})},// 删除图片delFile(e) {wx.showModal({title: '提示',content: '确定要删除吗?',success: res => {if (res.confirm) {let fileList = this.data.fileList;fileList.splice(parseInt(e.currentTarget.dataset.index), 1);this.setData({ fileList })this.triggerEvent("uploadFiles", {list: fileList,name: this.data.name});wx.showToast({title: '删除成功',icon: 'success',duration: 2000})}}})},// 预览图片viewImage(e) {let urls = this.data.fileList.map(item => { return item.url });wx.previewImage({current: e.currentTarget.dataset.url,urls});},}
})

uploadImg.less

.upload-wrap {.list-wrap {display: flex;flex-wrap: wrap;.item {position: relative;width: 188rpx;height: 188rpx;margin-top: 40rpx;margin-right: calc(~"(100% - 564rpx) / 3");.file {width: 100%;height: 100%;vertical-align: middle;border-radius: 8rpx;}.icon-delete {width: 40rpx;position: absolute;right: -10rpx;top: -10rpx;}}}.add-wrap {display: flex;align-items: center;justify-content: center;flex-direction: column;width: 188rpx;height: 188rpx;margin-top: 40rpx;border: 1px dashed #979797;border-radius: 8rpx;background-color: #f9fafb;text-align: center;.icon-camera {width: 50rpx;height: 46rpx;pointer-events: none;}}
}

 uploadImg.json

{"component": true,"usingComponents": {}
}

应用

<upload-img category="Personal" pageFileList="{{form.image}}" maxCount="3" disabled bind:uploadFiles="uploadFiles">
</upload-img>

 data: {form: {image: '[{"name":"Image","url":"https://wechatmp.uatwechat.com/upload/PersonalCompressed/20230614/20230614114423503.jpeg"}]',video: ''},},uploadFiles(e) {let str = "form." + e.detail.name;let list = e.detail.list;if (list.length > 0) {this.setData({[str]: JSON.stringify(e.detail.list)})} else {this.setData({[str]: '',})}},

app.alert方法封装 alert.js,然后在在app.js引入可使用

const show = (message, showCancel, successCallback = function() {}) => {wx.showModal({title: '提示',content: message,confirmColor: '#DB6276',showCancel: showCancel,success(res) {if (res.confirm) {successCallback();}}})
}module.exports = {show
}

小程序上传多张图片

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

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

相关文章

【自撰写】【国际象棋入门】第4课 局面分析初步

第4课 局面分析初步 一、国际象棋的棋局阶段划分 随着对弈的进行&#xff0c;国际象棋棋局可以划分为3个阶段&#xff0c;分别是开局阶段、中局阶段和残局阶段。简单说来&#xff0c;开局阶段主要完成子力的出动和布局&#xff1b;中局阶段涉及到更多的子力协同配合和子力兑换…

镭速是如何做到传输中快速校验大文件的

在信息泛滥的当下&#xff0c;文件传输系统的效率与安全性成为企业和个人用户高度关注的焦点。传统上&#xff0c;文件传输依赖于如MD5或XXHash等单一的完整性校验机制。 然而&#xff0c;在多变的工作环境中&#xff0c;这些传统方法显得不够灵活。镭速&#xff0c;作为大文件…

PostgreSQL源码分析——创建分区表

分区表&#xff0c;可以认为是逻辑上一张表&#xff0c;但实际上是将逻辑上的一张表&#xff0c;分割为了多个物理表&#xff0c;每个物理表是逻辑表中的一部分&#xff0c;组合起来就是一张表。所以在实现分区表时&#xff0c;实际上是创建了多张物理表&#xff0c;但是逻辑上…

【神经网络】深度神经网络

深度神经网络&#xff08;Deep Neural Network&#xff0c;简称DNN&#xff09;是一种模仿人脑神经网络结构和工作原理的机器学习模型。它通过层级化的特征学习和权重调节&#xff0c;能够实现复杂任务的高性能解决方案。深度神经网络由多个神经元层组成&#xff0c;每个神经元…

【尚庭公寓SpringBoot + Vue 项目实战】后台用户信息管理(十七)

【尚庭公寓SpringBoot Vue 项目实战】后台用户信息管理&#xff08;十七&#xff09; 文章目录 【尚庭公寓SpringBoot Vue 项目实战】后台用户信息管理&#xff08;十七&#xff09;1、业务说明2、逻辑模型介绍3、接口开发3.1、根据条件分页查询后台用户列表3.2、根据ID查询后…

【MySQL】复合查询和内外连接

文章目录 MySQL复合查询和内外连接1. 复合查询1.1 多表查询1.2 自连接1.3 子查询单行子查询多行子查询多列子查询from中使用子查询合并查询 2. 内外连接1. INNER JOIN2. LEFT JOIN3. RIGHT JOIN4. FULL JOIN5. CROSS JOIN MySQL复合查询和内外连接 1. 复合查询 1.1 多表查询 …

grafana连接influxdb2.x做数据大盘

连接influxdb 展示数据 新建仪表盘 选择存储库 设置展示

python字典转json

在Python中&#xff0c;你可以使用内置的json模块来轻松地将字典转换为JSON格式的字符串。下面是一个简单的示例&#xff1a; import json# 创建一个字典 data_dict {"name": "John Doe","age": 30,"city": "New York" }#…

Handler机制

目录 一、简介二、相关概念解释2.1 Message&#xff08;消息&#xff09;2.2 Handler&#xff08;处理器&#xff09;2.2.1 Handler的构造方法2.2.2 Handler sendMessage&#xff08;&#xff09;相关的方法2.2.3 Handler dispatchMessage&#xff08;&#xff09;方法 2.3 Mes…

NSSCTF-Web题目9

目录 [SWPUCTF 2021 新生赛]sql 1、题目 2、知识点 3、思路 [SWPUCTF 2022 新生赛]xff 1、题目 2、知识点 3、思路 [FSCTF 2023]源码&#xff01;启动! 1、题目 2、知识点 3、思路 [SWPUCTF 2021 新生赛]sql 1、题目 2、知识点 SQL注入&#xff0c;空格、注释符等…

vite 和webpack 的区别

1. 开发服务器启动速度 Vite: Vite 通过利用现代浏览器对 ES 模块的原生支持来提供快速的开发服务器启动。它在开发模式下不需要打包&#xff0c;而是直接提供源代码&#xff0c;这使得启动速度非常快。 Webpack: Webpack 在开发模式下需要构建整个应用&#xff0c;这通常需要…

京东和天猫各渠道区别是什么?你了解吗?如何快速了解两个平台渠道推广

1.快车/直通车区别: 京东:不能投竞品词,能投定向商品选竞品,因为京东是卖平台流量和商品(自营(主收入)),不可以投竞品词是为了保护自己店铺的品牌流量; 天猫:只卖平台流量,不卖商品,所以允许竞品词投放; 2.竞品人群圈选: 因为数坊是自身品牌数据分析平台,所…

【Python教程】如何压缩PDF减小文件大小?

压缩 PDF 文件能有效减小文件大小并提高文件传输的效率&#xff0c;同时还能节省计算机存储空间。除了使用一些专业工具对PDF文件进行压缩&#xff0c;我们还可以通过 Python 来执行该操作&#xff0c;实现自动化、批量处理PDF文件。 本文将分享一个简单有效的使用 Python 压缩…

基于Python引擎的PP-OCR模型库推理

基于Python引擎的PP-OCR模型库推理 1. 文本检测模型推理 # 下载超轻量中文检测模型&#xff1a; wget https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_det_infer.tar tar xf ch_PP-OCRv3_det_infer.tar python3 tools/infer/predict_det.py --image_dir"…

基于EXCEL数据表格创建省份专题地图

1 数据源 随着西藏于5月1日发布2022年一季度经济运行情况&#xff0c;31省份一季度GDP数据已全部出炉。 总量方面&#xff0c;粤苏鲁稳居前三&#xff1b;增速方面&#xff0c;23省份高于“全国线”&#xff0c;新疆表现最佳&#xff0c;增速达到7.0%。 表格表现数据不够直观…

算法第七天:leetcode之209.长度最小的子数组

一、长度最小的子数组 209.长度最小的子数组的链接&#xff1a;https://leetcode.cn/problems/minimum-size-subarray-sum/ 给定一个含有 n 个正整数的数组和一个正整数 target 。 找出该数组中满足其总和大于等于 target 的长度最小的 子数组[numsl, numsl1, ..., numsr-1, nu…

RPA助力企业办公流程自动化:真实应用案例展示

在当今快速变化的商业环境中&#xff0c;企业面临着前所未有的挑战和机遇。数字化转型已成为企业提升竞争力、优化运营效率和增强客户体验的关键策略。RPA数字员工作为这一转型过程中的重要工具&#xff0c;正在帮助企业实现办公流程的自动化&#xff0c;从而加速数字化转型的步…

[力扣题解] 701. 二叉搜索树中的插入操作

题目&#xff1a;701. 二叉搜索树中的插入操作 思路 二叉搜索树的查找规律&#xff1a;要插入的值val比当前节点大&#xff0c;往右走&#xff0c;比当前节点小&#xff0c;往左走&#xff1b; 代码 Method 1 class Solution { public:void travel(TreeNode* cur, int val…

Aeron:Multi-Destination-Cast

Multi-Destination-Cast&#xff08;MDC&#xff09;是一种功能&#xff0c;允许 Aeron 从单个 Publication 同时向多个目的地传送数据。Multiple-Destination-Cast是 Aeron 的一项高级功能&#xff0c;本指南将介绍如何开发一个简单示例的基本知识。 一、MDC Publications 注&…

正则表达式 - 在线工具

正则表达式 - 在线工具 正则表达式&#xff08;Regular Expression&#xff0c;简称Regex&#xff09;是一种强大的文本处理工具&#xff0c;它允许用户通过特定的模式匹配和操作字符串。在编程、数据分析和文本处理等领域&#xff0c;正则表达式被广泛应用。随着技术的发展&a…