Uniapp中图片上传完后再进行跳转或者其它操作的解决办法

在使用uniapp做多图片上传的时候,希望图片上传完毕后,再进行跳转,但代码写完后发现,图片尚未上传完毕后,页面已经跳转了,后来经过网上搜索,终于找到了办法。

那就是使用Promise

具体的可以参见https://juejin.cn/post/6881901884085534734

我将我的代码也贴出来,仅供参考,和之前的方法比较,主要是添加了下面红色部分的代码,其中要求

tasks里面push的方法,必须是返回Promise的

 

async uploadImg() {
				var that = this;
				let tasks = [];
				for (var i = 0; i < this.piclist.length; i++) {
					var imgIndex = padding0(i + 1, 3);
					var imgName = this.userInfo.studentNo + guid() + imgIndex + ".jpg";
					var data = {
						"testCourseID": this.testCourseID,
						"courseId": this.courseId,
						"studentCode": this.userInfo.schoolNumber,
						"classNum": this.userInfo.classNumber,
						"imgType": 0,
						"questionID": 0,
						"imgSum": this.piclist.length,
						"imgIndex": i + 1,
						"imgName": imgName,
					}
					console.log(i);
					tasks.push(that.uploadOne(data, i));
				}
				return Promise.all(tasks).then(function(result){
					console.info("dddd"+result);
					uni.redirectTo({
						url: "/pages/task/list"
					});
				});
			},
			 uploadOne(data, i) {
				var that = this;
				return new Promise((resolve,reject)=>{
				UpdateTestCouseImagePath(data).then((res) => {
					console.log('uploaded' + i + data.imgName);
					if (res.Status) {
						uni.uploadFile({
							url: MP_API_URL + 'UpdateTestCouseImgOneByOne', //仅为示例,非真实的接口地址
							filePath: that.piclist[i].url,
							name: 'file_1',
							formData: {
								"testCourseID": that.testCourseID,
								"imgName": data.imgName,
							},
							success: (uploadFileRes) => {
								console.log('that.testCourseID' + that.testCourseID);
								var res = that.processContent(uploadFileRes.data);
								if (res.Status) {
									uni.showToast({
										title: res.Msg,
										icon: 'none'
									});
                                   resolve();
								} else {
									uni.showToast({
										title: res.Msg,
										icon: 'none'
									});
									reject();
								}
							}
						});
					}
				});
				})
			},

  

posted @ 2022-07-30 17:47  sharestone  阅读(411)  评论(0编辑  收藏  举报