在for循环中使用FileTransfer插件将首次请求返回的postId传递给后续上传请求
核心问题
你当前的代码是并行触发所有图片的上传请求,第一个请求返回postId的时候,后续请求已经提前发送完成,自然无法携带正确的postId参数。另外你的uploadFileMedia方法存在笔误,resolve(res)中的res未定义,会导致上传后拿不到返回结果。
修复步骤
- 先修正
Camera Service.ts的笔误,补全错误抛出逻辑:
uploadFileMedia(path: string, url: string, fileType: string, post_id): Promise<any> { const fileTransfer: FileTransferObject = this.transfer.create(); let options: FileUploadOptions = { fileKey: 'images', fileName: fileType, params: {post_id: post_id } } return new Promise((resolve, reject) => { fileTransfer.upload(path, url, options).then((data) => { resolve(data) // 修正笔误,返回上传结果 }, (err) => { reject(err) // 抛出上传错误,方便上层捕获 }) }) }
- 修改
Page.page.ts的上传逻辑,优先上传第一张图片拿到postId后,再上传剩余图片:
// 拍照后上传入口 async takePhoto() { const photoList: any = await this.camera.takePhoto() if (!photoList?.length) return // 先上传第一张图,获取postId const firstItem = photoList[0] await this.uploadMedia(firstItem.fullPath, firstItem.fullPath.split('/').pop()) // 剩余图片并行上传,此时postId已经赋值完成 const restItems = photoList.slice(1) await Promise.all(restItems.map(item => { return this.uploadMedia(item.fullPath, item.fullPath.split('/').pop()) })) this.imgLoader = false // 全部上传完成后关闭加载状态 } // 单张图片上传方法 uploadMedia(path, type) { return this.camera.uploadFileMedia(path, 'UploadImage', type, this.postId).then((res: any) => { if (res.status == true) { // 仅第一次上传成功后赋值postId,后续上传复用该值 if (!this.postId) { this.postId = res.data.post_id } this.userImages.push({ img: res.data }) } }) }
逻辑说明
- 第一张图片上传时
postId为空,接口返回后完成赋值,后续所有上传请求都会携带该postId - 剩余图片采用并行上传,和你原有逻辑的上传效率几乎一致,不会额外增加耗时
- 所有上传方法都返回Promise,方便上层控制加载状态和后续逻辑
内容的提问来源于stack exchange,提问作者Najam Us Saqib
相关产品推荐
相关产品推荐

