【问题标题】:Uploading a file to GraphQL using Apollo Client使用 Apollo 客户端将文件上传到 GraphQL
【发布时间】:2020-12-04 04:20:32
【问题描述】:

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

到目前为止,我已经尝试使用另一个只需要一个字符串(而不是 $file 参数)的查询并且有效。所以 Apollo Client 似乎设置正确。我也尝试过使用 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
}

【问题讨论】:

  • 第一次 - 使用邮递员测试后端,第二次,发送文件,而不是内容/流等...将网络请求与邮递员进行比较
  • 感谢您的反馈。在测试时真正帮助我的工具是启用了“网络检查”选项的React Native Debugger。我找到了解决问题的方法(见下文)。

标签: android react-native graphql apollo-client react-native-fs


【解决方案1】:

我找到了解决问题的方法。 file 必须是 ReactNativeFile 类型(更多信息 here)。现在的代码如下所示:

...    
const file = new ReactNativeFile({
        uri: action.picture.uri,
        name: 'name.jpg',
        type: 'image/jpeg'
    });
...

还有一个带有 React Native 0.62+ 的 bug,它弄乱了多表单请求的配置。可以通过注释掉android/app/src/debug/java/com/maxyride/app/drivers/ReactNativeFlipper.java中的第43行来修复它:

//builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); 

【讨论】:

    猜你喜欢
    • 2021-03-19
    • 2021-04-04
    • 2019-01-15
    • 2021-05-30
    • 2019-06-22
    • 2020-04-27
    • 2021-05-18
    • 2020-12-01
    • 2019-12-31
    相关资源
    最近更新 更多