You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在for循环中使用FileTransfer插件将首次请求返回的postId传递给后续上传请求

核心问题

你当前的代码是并行触发所有图片的上传请求,第一个请求返回postId的时候,后续请求已经提前发送完成,自然无法携带正确的postId参数。另外你的uploadFileMedia方法存在笔误,resolve(res)中的res未定义,会导致上传后拿不到返回结果。

修复步骤

  1. 先修正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) // 抛出上传错误,方便上层捕获
      })
    })
}
  1. 修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 12:57:03