使用Apollo Client将文件上传到GraphQL

问题描述

我目前正在尝试将来自本地本机应用程序的文件(来自RNCamera的图像)上传到GraphQL后端。但是,后端始终返回状态码400

到目前为止,我已经尝试使用另一个只需要一个字符串(而不是$ file参数)并且有效的查询。因此,Apollo客户端似乎已正确设置。我也尝试过使用curl将文件发送到后端。效果也很好。

import { API_URL } from 'src/utils/config';    
import { ApolloClient,InMemoryCache,ApolloLink,gql } from '@apollo/client';
import { createUploadLink } from 'apollo-upload-client';
import { UPLOAD_PICTURE } from 'src/utils/query';

var RNFS = require('react-native-fs');

// Instantiate required constructor fields
const cache = new InMemoryCache();
const link = ApolloLink.from([
  createUploadLink({
    uri: API_URL
  })
]);

const client = new ApolloClient({
  // Provide required constructor fields
  cache: cache,link: link
});

执行突变:

// read the image that was saved as a file
const file = {
    file: await RNFS.readFile(action.picture.uri,'base64')
  };

// send the file to the backend
 client
    .mutate({
      mutation: gql(UPLOAD_PICTURE),variables: file
    })

通过src / utils / query:

export const UPLOAD_PICTURE = `
mutation ($file: Upload!){
  uploadFile(file: $file)
}
`;

后端的GraphQL模式:

type File {
    uri: String!
    filename: String!
    mimetype: String!
    encoding: String!
  }

//...

type Mutation {
  //...
  uploadFile(file: Upload!): File
}

解决方法

我找到了解决问题的方法。 @property def stages(self): return self.stage_set.all() 的类型必须为file(更多信息here)。现在的代码如下所示:

ReactNativeFile

还有一个bug,带有React Native 0.62+,它弄乱了多形式请求的配置。可以通过注释... const file = new ReactNativeFile({ uri: action.picture.uri,name: 'name.jpg',type: 'image/jpeg' }); ... 中的第43行来解决该问题:

android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...