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

iOS Apollo客户端对接NestJS GraphQL上传文件仅收到字符串问题求助

上传失败问题解决方案

核心问题原因

你遇到的问题是Apollo iOS上传参数配置不匹配,具体有两处错误:

  1. GraphQLFile的fieldName和mutation定义的上传参数名不一致
  2. 调用mutation时给上传参数传了静态字符串,而非留空让Apollo自动映射文件

具体修改步骤

1. 修正GraphQLFile的fieldName配置

Apollo iOS上传时,GraphQLFile的fieldName必须和你的mutation中定义的上传字段名完全一致。你当前mutation里的上传字段名为uploads,所以要把原来的fieldName: "avatar"改成fieldName: "uploads"。

2. 修正mutation调用的入参

调用CreateSellerProfileMutation时,uploads参数需要传nil,不要手动传字符串"avatar",Apollo会自动将files数组里的文件和mutation参数做映射。

3. 修正后的完整上传代码

let avaimg = avatarImage.jpegData(compressionQuality: 0.1)
// fieldName和mutation的上传参数名保持一致
let file = GraphQLFile(fieldName: "uploads", originalName: "avatar.jpg", mimeType: "image/jpeg", data: avaimg)
        
let sellerData = SellerInput(firstName: "phuong", lastName: "nguyen", description: "Hello, this is Phuong. I am freelance web developer")
// uploads参数传nil
Network.shared.apollo.upload(operation: CreateSellerProfileMutation(seller: sellerData, 
userId: "4d146299-a219-4bde-9874-bed936dda129", uploads: nil), files: [file]) {
       res in
       switch (res) {
       case .success(let graphQLResult):
            print("success")
       case .failure(let error):
            print("error: \(error)")
       }
}

服务端验证(如修改后仍有问题可排查)

确保NestJS端已经正确开启GraphQL上传支持:

  • 已安装graphql-upload依赖
  • Resolver中接收上传的参数类型为GraphQLUpload,示例如下:
import { Args, Mutation, Resolver } from '@nestjs/graphql';
import { GraphQLUpload, FileUpload } from 'graphql-upload';

@Resolver()
export class SellerResolver {
  @Mutation(() => Seller)
  async createSellerProfile(
    @Args('seller') seller: SellerInput,
    @Args('userId') userId: string,
    @Args('uploads') uploads: FileUpload,
  ) {
    // 处理文件逻辑
    const { createReadStream, filename, mimetype } = await uploads;
    // 后续业务逻辑
  }
}

内容的提问来源于stack exchange,提问作者Minh Phuong

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:09:01