I am trying to upload a GraphQL mutation and an image as application/form-data. The GraphQL part is working, but I would like to \'save\' the uploaded binary and add the pat
Spring boot's embedded Tomcat is defaulted to Servlet 3.x multipart support. GraphQL java servlet supports commons FileUpload. To make things work you have to disable Spring boots default multipart config, like:
Add maven dependency for commons-fileupload in pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
Application.yml
spring:
servlet:
multipart:
enabled: false
Spring Boot Application class
@EnableAutoConfiguration(exclude={MultipartAutoConfiguration.class})
And in your @Configuration add a @Bean
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000);
return multipartResolver;
}
Now you can find the uploaded multipart files in the GraphQL Context because they are automatically mapped to:
environment -> context -> files
Accessible from the DataFetchingEnvironment
And the implementation example of the mutation:
@Component
public class Mutation implements GraphQLMutationResolver {
@Autowired
private TokenService tokenService;
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
@Autowired
private ProjectRepository repository;
@Autowired
@Qualifier( value = "modeshape" )
private StorageService storageService;
@GraphQLField @GraphQLRelayMutation
public ProjectItem createProject( CreateProjectInput input, DataFetchingEnvironment environment ) {
Project project = new Project( input.getName() );
project.setDescription( input.getDescription() );
GraphQLContext context = environment.getContext();
Optional<Map<String, List<FileItem>>> files = context.getFiles();
files.ifPresent( keys -> {
List<FileItem> file = keys.get( "file" );
List<StorageService.FileInfo> storedFiles = file.stream().map( f -> storageService.store( f, "files", true ) ).collect( Collectors.toList() );
project.setFile( storedFiles.get( 0 ).getUuid() );
} );
repository.save( project );
return new ProjectItem( project );
}
class CreateProjectInput {
private String name;
private String description;
private String clientMutationId;
@GraphQLField
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public void setDescription( String description ) {
this.description = description;
}
@GraphQLField
public String getClientMutationId() {
return clientMutationId;
}
}