How to upload files with graphql-java?

后端 未结 3 1483
情书的邮戳
情书的邮戳 2020-12-17 01:49

I can\'t find out how to upload files if i use graphql-java, can someone show me a demo? I will be appreciated!

reference : https://github.com/graphql-java-kickstar

3条回答
  •  情歌与酒
    2020-12-17 02:23

    Just to add onto the answers above, for anyone like me who could find 0 examples of file upload with the GraphQLSchemaGenerator vs the schema first approach, you have to just create a TypeMapper and add that to your GraphQLSchemaGenerator:

    public class FileUploadMapper implements TypeMapper {
    
      @Override
      public GraphQLOutputType toGraphQLType(
          final AnnotatedType javaType, final OperationMapper operationMapper,
          final Set> mappersToSkip, final BuildContext buildContext) {
        return MyScalars.FileUpload;
      }
    
      @Override
      public GraphQLInputType toGraphQLInputType(
          final AnnotatedType javaType, final OperationMapper operationMapper,
          final Set> mappersToSkip, final BuildContext buildContext) {
        return MyScalars.FileUpload;
      }
    
      @Override
      public boolean supports(final AnnotatedType type) {
         return type.getType().equals(FileUpload.class); //class of your fileUpload POJO from the previous answer
      }
    }
    

    then in your GraphQL @Configuration file where you are building your GraphQLSchema:

    public GraphQLSchema schema(GraphQLSchemaGenerator schemaGenerator) {
        return schemaGenerator
            .withTypeMappers(new FileUploadMapper()) //add this line
            .generate();
      }
    

    Then in your mutation resolver

      @GraphQLMutation(name = "fileUpload")
      public void fileUpload(      
          @GraphQLArgument(name = "file") FileUpload fileUpload //type here must be the POJO.class referenced in your TypeMapper
      ) {
        //do something with the byte[] from fileUpload.getContent();
        return;
      }
    

提交回复
热议问题