Angular/Apollo GraphQL文件上传报错:需配置extractFiles函数
Angular + Apollo GraphQL 文件上传配置方案
解决步骤
1. 安装依赖库
首先安装报错提示中提到的extract-files库,它负责从请求变量中提取文件并转换为符合上传规范的格式:
npm install extract-files # 或使用yarn yarn add extract-files
2. 配置Apollo HttpLink
在Angular的Apollo配置文件(通常是app.module.ts或单独的Apollo配置文件)中,导入extractFiles函数并添加到HttpLink的配置项里:
import { NgModule } from '@angular/core'; import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular'; import { HttpLink } from 'apollo-angular/http'; import { InMemoryCache } from '@apollo/client/core'; // 导入extract-files的核心函数 import { extractFiles } from 'extract-files'; @NgModule({ imports: [ApolloModule], providers: [ { provide: APOLLO_OPTIONS, useFactory: (httpLink: HttpLink) => { return { cache: new InMemoryCache(), link: httpLink.create({ uri: '/your-graphql-endpoint', // 替换为你的服务端GraphQL地址 // 添加extractFiles配置,解决上传报错 extractFiles: extractFiles }), }; }, deps: [HttpLink], }, ], }) export class GraphQLModule {}
3. 调用上传Mutation示例
在组件中构造包含文件的请求变量,调用上传Mutation即可正常发起文件上传请求:
import { Component } from '@angular/core'; import { Apollo } from 'apollo-angular'; import gql from 'graphql-tag'; // 定义上传Mutation const UPLOAD_FILE_MUTATION = gql` mutation UploadFile($file: Upload!) { uploadFile(file: $file) { id filename mimetype size } } `; @Component({ selector: 'app-file-upload', template: `<input type="file" (change)="handleFileUpload($event)">` }) export class FileUploadComponent { constructor(private apollo: Apollo) {} handleFileUpload(event: Event): void { const file = (event.target as HTMLInputElement).files?.[0]; if (!file) return; this.apollo.mutate({ mutation: UPLOAD_FILE_MUTATION, variables: { file: file } }).subscribe({ next: (res) => console.log('文件上传成功:', res.data), error: (err) => console.error('文件上传失败:', err) }); } }
原理说明
Postman会自动识别请求中的文件并转换为multipart/form-data格式,但Apollo Angular需要通过extractFiles函数手动处理变量中的File对象,将请求转换为符合GraphQL文件上传规范的格式,从而匹配你服务端基于graphql-upload-ts的处理逻辑。
内容的提问来源于stack exchange,提问作者CaNa
相关产品推荐
相关产品推荐

