How to upload files with graphql-java?

后端 未结 3 1480
情书的邮戳
情书的邮戳 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:16

    1. define a scalar type in our schema

      scalar Upload

      and we should configure GraphQLScalarType for Upload, use this below:

      @Configuration
      public class GraphqlConfig {
      
         @Bean
         public GraphQLScalarType uploadScalarDefine() {
            return ApolloScalars.Upload;
         } 
      }
      
    2. then we would define a mutation in schema and a GraphQLMutationResolver for testMultiFilesUpload

      type Mutation {
        testMultiFilesUpload(files: [Upload!]!): Boolean
      }
      

    here is Resolver:

    public Boolean testMultiFilesUpload(List parts, DataFetchingEnvironment env) {
        // get file parts from DataFetchingEnvironment, the parts parameter is not use
        List attachmentParts = env.getArgument("files");
        int i = 1;
        for (Part part : attachmentParts) {
          String uploadName = "copy" + i;
          try {
            part.write("your path:" + uploadName);
          } catch (IOException e) {
            e.printStackTrace();
          }
          i++;
        }
        return true;   
      }
    }
    
    1. configure a jackson deserializer for javax.servlet.http.Part and register it to ObjectMapper

      public class PartDeserializer extends JsonDeserializer {
      
        @Override
        public Part deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {         
           return null;
        }
      }
      

      why we return null? because the List parts always null ,In the resolver's method, get the parts argument from the DataFetchingEnvironment;

      environment.getArgument("files")

    register it to ObjectMapper:

    @Bean
    public ObjectMapper objectMapper() {
      ObjectMapper objectMapper = new ObjectMapper();
      objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
      SimpleModule module = new SimpleModule();
      module.addDeserializer(Part.class, new PartDeserializer());
      objectMapper.registerModule(module);
      return objectMapper;
    }
    
    1. To test this, post the following form data (we use Postman) to GraphQL endpoint
    operations
    
    { "query": "mutation($files: [Upload!]!) {testMultiFilesUpload(files:$files)}", "variables": {"files": [null,null] } }
    
    map
    
    { "file0": ["variables.files.0"] , "file1":["variables.files.1"]}
    
    file0
    
    your file
    
    file1
    
    your file
    

    like this:

    remember to select the form-data option

    through this we can upload multiple files

提交回复
热议问题