【发布时间】: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