简体   繁体   English

如何使用Relay Modern突变进行文件上传?

[英]How to do file uploads with Relay Modern mutations?

I'm using react-relay/compat 1.1.0 and I need to write a mutation with the ability to upload a file. 我正在使用react-relay/compat 1.1.0 ,我需要编写一个能够上传文件的变异。 In Relay Classic you can use getFiles() to support file uploads in mutations: 在Relay Classic中,您可以使用getFiles()来支持突变中的文件上传:

class AddImageMutation extends Relay.Mutation {
   getMutation() {
     return Relay.QL`mutation{ introduceImage }`;
   }

   getFiles() {
     return {
       file: this.props.file,
     };
   }
   ...
}

But haven't found any trace of functionality for uploading files in Relay Modern docs: 但是在Relay Modern文档中没有找到任何上传文件的功能:

const {commitMutation} = require('react-relay');

commitMutation(
  environment: Environment,
  config: {
    mutation: GraphQLTaggedNode,
    variables: Variables,
    onCompleted?: ?(response: ?Object) => void,
    onError?: ?(error: Error) => void,
    optimisticResponse?: ?() => Object,
    optimisticUpdater?: ?(store: RecordSourceSelectorProxy) => void,
    updater?: ?(store: RecordSourceSelectorProxy) => void,
    configs?: Array<RelayMutationConfig>,

    // files: ... ?
  },
);

Is that supported yet in relay modern? 接力现代还支持吗? and if so, what's the way of doing it? 如果是这样,这样做的方式是什么? Thanks. 谢谢。

You have to provide the files as object uploadables in the config object for commitMutation and then implement the actual upload in your Network Layer, because the fetch request to the server has to be a multipart form and not application/json. 您必须在commitMutationconfig对象中提供文件作为对象uploadables文件,然后在网络层中实现实际上载,因为对服务器的提取请求必须是多部分表单而不是application / json。

See https://github.com/facebook/relay/issues/1844#issuecomment-316893590 for a complete example. 有关完整示例,请参阅https://github.com/facebook/relay/issues/1844#issuecomment-316893590

Found this question as I just had the same one myself. 发现这个问题,因为我自己也有同样的问题。

Not sure of the complete answer yet, but I'm starting to read through the Relay source and based on packages/relay-runtime/mutations/commitRelayModernMutation.js it looks like you can pass uploadables to your mutation. 不知道完整的答案还没有,但我开始通过继电器读取源和基于包/继电器运行时/突变/ commitRelayModernMutation.js它看起来像你可以通过uploadables你的突变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM