如何解决使用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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。