{"id":126110,"date":"2024-09-19T14:49:00","date_gmt":"2024-09-19T11:49:00","guid":{"rendered":"https:\/\/www.javacodegeeks.com\/?p=126110"},"modified":"2024-09-18T14:03:54","modified_gmt":"2024-09-18T11:03:54","slug":"upload-files-with-graphql-in-java","status":"publish","type":"post","link":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html","title":{"rendered":"Upload Files With GraphQL in Java"},"content":{"rendered":"<p>File uploads are a common feature in modern applications, and GraphQL can handle them with some customization. GraphQL doesn&#8217;t natively support file uploads out of the box, and managing file uploads in a GraphQL API involves a few additional steps compared to traditional REST APIs. This article will guide us through creating a Spring Boot application that enables file uploads via GraphQL.<\/p>\n<h2 class=\"wp-block-heading\">1. Introduction to File Upload with GraphQL<\/h2>\n<p>Standard GraphQL doesn&#8217;t support file uploads natively. GraphQL typically works with JSON-based queries, and files like images or documents don&#8217;t fit into this format. However, we can work around this limitation by using the multipart form data format, which allows files to be transmitted alongside the GraphQL query in a single request.<\/p>\n<p>By defining a custom scalar type called <code>Upload<\/code>, we can handle file uploads within the GraphQL framework, making it easy to integrate file handling into our GraphQL API.<\/p>\n<h2 class=\"wp-block-heading\">2. Dependencies<\/h2>\n<p>In this section, we&#8217;ll add the required dependencies to set up our GraphQL application and enable file uploads. Set up a Spring Boot project which can be done by using <a href=\"https:\/\/start.spring.io\/\" target=\"_blank\" rel=\"noreferrer noopener\">Spring Initializr<\/a> to create a project with the following necessary dependencies:<\/p>\n<pre class=\"brush:xml\">\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-boot-starter-graphql&lt;\/artifactId&gt;\n        &lt;\/dependency&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-boot-starter-web&lt;\/artifactId&gt;\n        &lt;\/dependency&gt;\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-boot-starter-webflux&lt;\/artifactId&gt;\n            &lt;scope&gt;test&lt;\/scope&gt;\n        &lt;\/dependency&gt;\t\n        &lt;dependency&gt;\n            &lt;groupId&gt;org.springframework.graphql&lt;\/groupId&gt;\n            &lt;artifactId&gt;spring-graphql-test&lt;\/artifactId&gt;\n            &lt;scope&gt;test&lt;\/scope&gt;\n        &lt;\/dependency&gt;\n<\/pre>\n<h2 class=\"wp-block-heading\">2. Define Schema for File Upload<\/h2>\n<p>In GraphQL, scalars are used to define custom data types. Here, we define a <code>Upload<\/code> scalar to represent file uploads. Create a new file called <code>src\/main\/resources\/graphql\/mutation.graphqls<\/code> and add the following content to define the upload operation. <\/p>\n<p>This GraphQL schema defines the structure for a simple file upload mutation. <\/p>\n<pre class=\"brush:java\">\nscalar Upload\n\ntype Mutation {\n    uploadFile(file: Upload!): String\n}\n\ntype Query {\n    getFile: String\n}\n<\/pre>\n<p>In this code, the <code>uploadFile<\/code> mutation expects one parameter: a file of type <code>Upload<\/code>. The custom scalar type <code>Upload<\/code> will be mapped to a <code>MultipartFile<\/code>, allowing us to process the file upload.<\/p>\n<h2 class=\"wp-block-heading\">3. Handle Upload Scalar with <code>Coercing<\/code><\/h2>\n<p>In the context of GraphQL, <strong>coercing<\/strong> refers to the process of converting data between the format used by the GraphQL schema and the format received or sent in the API requests and responses. This is important for custom scalar types or complex data formats. <\/p>\n<p>To handle the <code>Upload<\/code> scalar, we need to implement a custom coercing class that manages how the <code>MultipartFile<\/code> object is processed.<\/p>\n<pre class=\"brush:java\">\nimport graphql.schema.Coercing;\nimport graphql.schema.CoercingParseLiteralException;\nimport graphql.schema.CoercingParseValueException;\nimport graphql.schema.CoercingSerializeException;\nimport org.springframework.web.multipart.MultipartFile;\n\n\npublic class UploadCoercing implements Coercing&lt;MultipartFile, MultipartFile&gt; {\n\n    @Override\n    public MultipartFile serialize(Object dataFetcherResult) throws CoercingSerializeException {\n        throw new CoercingSerializeException(\"Upload is an input-only type\");\n    }\n\n    @Override\n    public MultipartFile parseValue(Object input) throws CoercingParseValueException {\n        if (input instanceof MultipartFile) {\n            return (MultipartFile) input;\n        }\n        throw new CoercingParseValueException(\n            String.format(\"Expected a 'MultipartFile' like object but was '%s'.\", input != null ? input.getClass() : null)\n        );\n    }\n\n    @Override\n    public MultipartFile parseLiteral(Object input) throws CoercingParseLiteralException {\n        throw new CoercingParseLiteralException(\"Parsing literal of 'MultipartFile' is not supported\");\n    }\n}\n\n<\/pre>\n<p>The <code>UploadCoercing<\/code> class defines how the <code>Upload<\/code> scalar is interpreted. The <code>parseValue<\/code> method ensures that the input is of type <code>MultipartFile<\/code>, and it throws exceptions for unsupported operations like serialization and parsing literals. This coercing logic is essential to safely process file uploads and prevent unsupported operations.<\/p>\n<h2 class=\"wp-block-heading\">4. Handling Multipart Requests<\/h2>\n<p>This section contains the <code>GraphqlMultipartHandler<\/code> class, which processes multipart form-data requests, extracts file uploads, and maps them to GraphQL query variables.<\/p>\n<pre class=\"brush:java\">\npublic class GraphqlMultipartHandler {\n\n    \/\/ A handler to process GraphQL requests\n    private final WebGraphQlHandler graphQlHandler;\n\n    \/\/ ObjectMapper used to convert between JSON and Java objects\n    private final ObjectMapper objectMapper;\n\n    \/\/ Constructor that initializes the handler and object mapper with null checks\n    public GraphqlMultipartHandler(WebGraphQlHandler graphQlHandler, ObjectMapper objectMapper) {\n        Assert.notNull(graphQlHandler, \"WebGraphQlHandler is required\");\n        Assert.notNull(objectMapper, \"ObjectMapper is required\");\n        this.graphQlHandler = graphQlHandler;\n        this.objectMapper = objectMapper;\n    }\n\n    \/\/ Supported media types for the GraphQL response (GraphQL and JSON)\n    public static final List&lt;MediaType&gt; SUPPORTED_RESPONSE_MEDIA_TYPES\n            = Arrays.asList(MediaType.APPLICATION_GRAPHQL, MediaType.APPLICATION_JSON);\n\n    private static final Log logger = LogFactory.getLog(GraphQlHttpHandler.class);\n\n    private final IdGenerator idGenerator = new AlternativeJdkIdGenerator();\n\n    \/\/ Main method to handle the incoming multipart GraphQL request\n    public ServerResponse handleRequest(ServerRequest serverRequest) throws ServletException {\n        \/\/ Read the 'operations' parameter from the request\n        Optional&lt;String&gt; operation = serverRequest.param(\"operations\");\n\n        \/\/ Read the 'map' parameter which maps files to query variables\n        Optional&lt;String&gt; mapParam = serverRequest.param(\"map\");\n\n        \/\/ Parse the 'operations' JSON into a Map\n        Map&lt;String, Object&gt; inputQuery = readJson(operation, new TypeReference&lt;&gt;() {});\n\n        \/\/ Extract query variables from the input query\n        final Map&lt;String, Object&gt; queryVariables;\n        if (inputQuery.containsKey(\"variables\")) {\n            queryVariables = (Map&lt;String, Object&gt;) inputQuery.get(\"variables\");\n        } else {\n            queryVariables = new HashMap&lt;&gt;();\n        }\n\n        \/\/ Handle extensions if present in the request\n        Map&lt;String, Object&gt; extensions = new HashMap&lt;&gt;();\n        if (inputQuery.containsKey(\"extensions\")) {\n            extensions = (Map&lt;String, Object&gt;) inputQuery.get(\"extensions\");\n        }\n\n        \/\/ Read the file parts from the multipart body\n        Map&lt;String, MultipartFile&gt; fileParams = readMultipartBody(serverRequest);\n\n        \/\/ Parse the 'map' JSON to associate files with variables\n        Map&lt;String, List&lt;String&gt;&gt; fileMapInput = readJson(mapParam, new TypeReference&lt;&gt;() {});\n\n        \/\/ Map each file to its corresponding variable path in the GraphQL query\n        fileMapInput.forEach((String fileKey, List&lt;String&gt; objectPaths) -&gt; {\n            MultipartFile file = fileParams.get(fileKey);\n            if (file != null) {\n                objectPaths.forEach((String objectPath) -&gt; {\n                    MultipartVariableMapper.mapVariable(\n                            objectPath,\n                            queryVariables,\n                            file\n                    );\n                });\n            }\n        });\n\n        \/\/ Extract the actual GraphQL query and operation name\n        String query = (String) inputQuery.get(\"query\");\n        String opName = (String) inputQuery.get(\"operationName\");\n\n        \/\/ Remote address and cookies (if needed) for the request\n        InetSocketAddress remoteAddress = null;\n        MultiValueMap&lt;String, HttpCookie&gt; cookies = null;\n\n        \/\/ Build the request body including query, variables, and extensions\n        Map&lt;String, Object&gt; body = new HashMap&lt;&gt;();\n        body.put(\"query\", query);\n        body.put(\"operationName\", StringUtils.hasText(opName) ? opName : \"\");\n        body.put(\"variables\", queryVariables);\n        body.put(\"extensions\", extensions);\n\n        \/\/ Create a WebGraphQlRequest that wraps all the information required for processing\n        WebGraphQlRequest graphQlRequest = new WebGraphQlRequest(serverRequest.uri(),\n                 serverRequest.headers().asHttpHeaders(), cookies,\n                 remoteAddress, queryVariables,\n                 body, this.idGenerator.generateId().toString(), LocaleContextHolder.getLocale()\n        );\n\n        if (logger.isDebugEnabled()) {\n            logger.debug(\"Executing: \" + graphQlRequest);\n        }\n\n        \/\/ Execute the request and return the server response as an asynchronous result\n        Mono&lt;ServerResponse&gt; responseMono = this.graphQlHandler.handleRequest(graphQlRequest)\n                .map(response -&gt; {\n                    if (logger.isDebugEnabled()) {\n                        logger.debug(\"Execution complete\");\n                    }\n                    \/\/ Build the response with appropriate headers and content type\n                    ServerResponse.BodyBuilder builder = ServerResponse.ok();\n                    builder.headers(headers -&gt; headers.putAll(response.getResponseHeaders()));\n                    builder.contentType(selectResponseMediaType(serverRequest));\n                    return builder.body(response.toMap());\n                });\n\n        \/\/ Return the async server response\n        return ServerResponse.async(responseMono);\n    }\n}\n\n<\/pre>\n<p>The <code>GraphqlMultipartHandler<\/code> class is responsible for handling multipart file uploads in GraphQL requests. It integrates a <code><a href=\"https:\/\/docs.spring.io\/spring-graphql\/docs\/1.0.0-SNAPSHOT\/javadoc-api\/org\/springframework\/graphql\/web\/WebGraphQlHandler.html\" target=\"_blank\" rel=\"noreferrer noopener\">WebGraphQlHandler<\/a><\/code> for processing the core GraphQL logic and an <code>ObjectMapper<\/code> for JSON parsing. The main functionality involves reading the incoming request, extracting the GraphQL query and associated variables, mapping file uploads to the appropriate GraphQL query parameters, and finally, executing the request and returning the appropriate response. <div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<p>The handler supports both GraphQL and JSON media types and is designed to handle multipart forms, mapping files to GraphQL variables via a <code>map<\/code> parameter. The <code>handleRequest<\/code> method reads the file and query from the multipart body, logs the request, and processes it asynchronously. It parses the operation and maps parameters from the request, ensuring that uploaded files are correctly assigned to the variables in the query. The response is then built using appropriate headers and media types. <\/p>\n<p>The class also includes utility methods like <code>readJson<\/code> for parsing JSON data and <code>readMultipartBody<\/code> for handling the file content. The full source code of this class can be downloaded from the link provided at the end of this article.<\/p>\n<h2 class=\"wp-block-heading\">5. File Upload Data Fetcher<\/h2>\n<p>In this part of the article, we create a <code>DataFetcher<\/code> to manage the file upload mutation. The <code>GraphQLFileUploader<\/code> works with the <code>FileStorageService<\/code> to save the file and return the file path after a successful upload.<\/p>\n<pre class=\"brush:java\">\nimport graphql.schema.DataFetcher;\nimport graphql.schema.DataFetchingEnvironment;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.multipart.MultipartFile;\n\n\n@Component\npublic class GraphQLFileUploader implements DataFetcher&lt;String&gt; {\n    private final FileStorageService fileStorageService;\n\n    public GraphQLFileUploader(FileStorageService fileStorageService) {\n        this.fileStorageService = fileStorageService;\n    }\n\n    @Override\n    public String get(DataFetchingEnvironment environment) {\n        MultipartFile file = environment.getArgument(\"file\");\n        \n        String storedFilePath = fileStorageService.store(file);\n        return String.format(\"File stored at: %s\", storedFilePath);\n    }\n}\n<\/pre>\n<p>The <code>GraphQLFileUploader<\/code> class is a Spring component that handles file uploads in a GraphQL API by implementing the <code>DataFetcher<\/code> interface. It retrieves the file from the <code>DataFetchingEnvironment<\/code> during a GraphQL mutation and uses the <code>FileStorageService<\/code> to store the file. In the <code>get()<\/code> method, the file is extracted from the mutation request, passed to the <code>FileStorageService<\/code> for saving, and a confirmation message with the file&#8217;s storage path is returned.<\/p>\n<h3 class=\"wp-block-heading\">5.1 File Storage Service<\/h3>\n<p>In this section, we define the <code>FileStorageService<\/code> class, which handles the storage of uploaded files. <\/p>\n<pre class=\"brush:java\">\nimport org.springframework.stereotype.Service;\nimport org.springframework.web.multipart.MultipartFile;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.Objects;\n\n@Service\npublic class FileStorageService {\n\n    private final Path rootLocation = Paths.get(\"uploads\");\n\n    public FileStorageService() {\n        try {\n            Files.createDirectories(rootLocation);\n        } catch (IOException e) {\n            throw new RuntimeException(\"Failed to initialize the storage location.\", e);\n        }\n    }\n\n    public String store(MultipartFile file) {\n        try {\n            if (file.isEmpty()) {\n                throw new RuntimeException(\"Failed to store empty file.\");\n            }\n            Path destination = rootLocation.resolve(\n                            Paths.get(Objects.requireNonNull(file.getOriginalFilename())))\n                    .normalize().toAbsolutePath();\n            file.transferTo(destination);\n            return String.format(\"File uploaded successfully: %s\", destination);\n        } catch (IOException e) {\n            throw new RuntimeException(\"Failed to store file.\", e);\n        }\n    }\n}\n<\/pre>\n<p>The <code>FileStorageService<\/code> class handles file storage in the application. It initializes with an <code>uploads<\/code> directory and ensures it exists. If directory creation fails, an exception is thrown. The <code>store<\/code> method saves the <code>MultipartFile<\/code> to the specified directory (a directory named <code>uploads<\/code>, which is located relative to the application&#8217;s working directory).<\/p>\n<h2 class=\"wp-block-heading\">6. GraphQL Configuration<\/h2>\n<p>This section covers configuring the GraphQL server to recognize the <code>Upload<\/code> scalar and route file uploads properly.<\/p>\n<pre class=\"brush:java\">\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport static com.jcg.GraphqlMultipartHandler.SUPPORTED_RESPONSE_MEDIA_TYPES;\nimport graphql.schema.GraphQLScalarType;\nimport static graphql.schema.idl.TypeRuntimeWiring.newTypeWiring;\nimport org.springframework.boot.autoconfigure.graphql.GraphQlProperties;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.core.annotation.Order;\nimport org.springframework.graphql.execution.RuntimeWiringConfigurer;\nimport org.springframework.graphql.server.WebGraphQlHandler;\nimport org.springframework.http.MediaType;\nimport static org.springframework.http.MediaType.MULTIPART_FORM_DATA;\nimport org.springframework.web.servlet.function.RequestPredicates;\nimport org.springframework.web.servlet.function.RouterFunction;\nimport org.springframework.web.servlet.function.RouterFunctions;\nimport org.springframework.web.servlet.function.ServerResponse;\n\n\n@Configuration\npublic class GraphqlConfiguration {\n\n    private final GraphQLFileUploader fileUploadDataFetcher;\n\n    public GraphqlConfiguration(GraphQLFileUploader fileUploadDataFetcher) {\n        this.fileUploadDataFetcher = fileUploadDataFetcher;\n    }\n\n    @Bean\n    public RuntimeWiringConfigurer runtimeWiringConfigurer() {\n        return (builder) -&gt; builder\n                .type(newTypeWiring(\"Mutation\").dataFetcher(\"uploadFile\", fileUploadDataFetcher))\n                .scalar(GraphQLScalarType.newScalar()\n                        .name(\"Upload\")\n                        .coercing(new UploadCoercing())\n                        .build());\n    }\n\n    @Bean\n    @Order(1)\n    public RouterFunction&lt;ServerResponse&gt; graphQlMultipartRouterFunction(\n            GraphQlProperties properties,\n            WebGraphQlHandler webGraphQlHandler,\n            ObjectMapper objectMapper\n    ) {\n        String path = properties.getPath();\n        RouterFunctions.Builder builder = RouterFunctions.route();\n        GraphqlMultipartHandler graphqlMultipartHandler = new GraphqlMultipartHandler(webGraphQlHandler, objectMapper);\n        builder = builder.POST(path, RequestPredicates.contentType(MULTIPART_FORM_DATA)\n                .and(RequestPredicates.accept(SUPPORTED_RESPONSE_MEDIA_TYPES.toArray(MediaType[]::new))), graphqlMultipartHandler::handleRequest);\n        return builder.build();\n    }\n}\n\n<\/pre>\n<p>The <code>GraphqlConfiguration<\/code> class configures GraphQL for handling file uploads. The <code>runtimeWiringConfigurer<\/code> method sets up a data fetcher for the <code>uploadFile<\/code> mutation and defines a custom <code>Upload<\/code> scalar type with the <code>UploadCoercing<\/code> implementation. This method ensures that file upload operations are correctly wired in the GraphQL schema.<\/p>\n<p>The <code>graphQlMultipartRouterFunction<\/code> method establishes routing for multipart form-data requests. It creates a <code>RouterFunction<\/code> that directs POST requests with <code>MULTIPART_FORM_DATA<\/code> content to the <code>GraphqlMultipartHandler<\/code>, which processes the file uploads. This setup enables efficient handling of file uploads in the GraphQL API.<\/p>\n<h2 class=\"wp-block-heading\">7. Testing the File Upload API<\/h2>\n<p>We can test the file upload API using curl commands. Here&#8217;s an example curl request (replace the file path with your actual file location):<\/p>\n<pre class=\"brush:bash\">\ncurl --location --request POST 'http:\/\/localhost:8080\/graphql' --form 'operations={\"query\": \"mutation UploadFile($file: Upload!) { uploadFile(file: $file) }\", \"variables\": {\"file\": null}}' --form 'map={\"file\": [\"variables.file\"]}' --form 'file=@\"\/Users\/omozegieaziegbe\/Downloads\/phoneicon.jpeg\"'\n\n<\/pre>\n<p>The <code>POST<\/code> request to the GraphQL endpoint is structured to handle file uploads using multipart form-data. The <code>operations<\/code> form field specifies the GraphQL mutation <code>UploadFile<\/code>, which requires a <code>file<\/code> parameter. This field includes the GraphQL query and the variables for the mutation, detailing what operation to perform and which data to use.<\/p>\n<p>The <code>map<\/code> form field links the uploaded file to the mutation variable <code>variables.file<\/code>, ensuring the server correctly associates the file with the mutation parameter. The <code>file<\/code> form field includes the actual file data, provided via a file path. Together, these components enable the file to be sent and processed correctly by the GraphQL server. <\/p>\n<p>Upon a successful file upload POST request, the response will confirm the file was uploaded successfully. Here\u2019s what to expect in the output:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><a href=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/09\/graphqlfileupload.png\"><img decoding=\"async\" width=\"586\" height=\"59\" src=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/09\/graphqlfileupload.png\" alt=\"java graphql upload file example output\" class=\"wp-image-126531\" srcset=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/09\/graphqlfileupload.png 586w, https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/09\/graphqlfileupload-300x30.png 300w\" sizes=\"(max-width: 586px) 100vw, 586px\" \/><\/a><figcaption class=\"wp-element-caption\">Java GraphQL File Upload Output: Example of successful file upload response<\/figcaption><\/figure>\n<\/div>\n<h2 class=\"wp-block-heading\">8. Conclusion<\/h2>\n<p>In this article, we explored how to implement file upload functionality in a Java GraphQL application using Spring Boot. We covered handling multipart requests and creating a DataFetcher to manage file uploads. By the end, we demonstrated how to test the implementation using a sample curl request. With these steps, we can incorporate file uploads into our own GraphQL APIs.<\/p>\n<h2 class=\"wp-block-heading\">9. Download the Source Code<\/h2>\n<p>This article focuses on implementing Java GraphQL upload file functionality.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <a href=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2024\/09\/graphqluploadfiles.zip\"><strong>java graphql upload file<\/strong><\/a>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>File uploads are a common feature in modern applications, and GraphQL can handle them with some customization. GraphQL doesn&#8217;t natively support file uploads out of the box, and managing file uploads in a GraphQL API involves a few additional steps compared to traditional REST APIs. This article will guide us through creating a Spring Boot &hellip;<\/p>\n","protected":false},"author":128888,"featured_media":117826,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[1458,854],"class_list":["post-126110","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-enterprise-java","tag-graphql","tag-spring-boot"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Upload Files With GraphQL in Java - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"Learn how to implement Java GraphQL upload file functionality in a Spring Boot API with comprehensive step-by-step guidance.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Upload Files With GraphQL in Java - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"Learn how to implement Java GraphQL upload file functionality in a Spring Boot API with comprehensive step-by-step guidance.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html\" \/>\n<meta property=\"og:site_name\" content=\"Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:author\" content=\"https:\/\/web.facebook.com\/omos.aziegbe\" \/>\n<meta property=\"article:published_time\" content=\"2024-09-19T11:49:00+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2023\/06\/graphql-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Omozegie Aziegbe\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/OAziegbe\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Omozegie Aziegbe\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html\"},\"author\":{\"name\":\"Omozegie Aziegbe\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/7d3eac6e45542536e961129ae0fb453e\"},\"headline\":\"Upload Files With GraphQL in Java\",\"datePublished\":\"2024-09-19T11:49:00+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html\"},\"wordCount\":1096,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2023\\\/06\\\/graphql-logo.jpg\",\"keywords\":[\"GraphQL\",\"Spring Boot\"],\"articleSection\":[\"Enterprise Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html\",\"name\":\"Upload Files With GraphQL in Java - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2023\\\/06\\\/graphql-logo.jpg\",\"datePublished\":\"2024-09-19T11:49:00+00:00\",\"description\":\"Learn how to implement Java GraphQL upload file functionality in a Spring Boot API with comprehensive step-by-step guidance.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html#primaryimage\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2023\\\/06\\\/graphql-logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2023\\\/06\\\/graphql-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/upload-files-with-graphql-in-java.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Enterprise Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\\\/enterprise-java\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Upload Files With GraphQL in Java\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Developers Resource Center\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.javacodegeeks.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/javacodegeeks\",\"https:\\\/\\\/x.com\\\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/7d3eac6e45542536e961129ae0fb453e\",\"name\":\"Omozegie Aziegbe\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2023\\\/12\\\/cropped-jcg_profile_pic-96x96.jpg\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2023\\\/12\\\/cropped-jcg_profile_pic-96x96.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2023\\\/12\\\/cropped-jcg_profile_pic-96x96.jpg\",\"caption\":\"Omozegie Aziegbe\"},\"description\":\"Omos Aziegbe is a technical writer and web\\\/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.\",\"sameAs\":[\"https:\\\/\\\/web.facebook.com\\\/omos.aziegbe\",\"https:\\\/\\\/www.linkedin.com\\\/in\\\/omosaziegbe\\\/\",\"https:\\\/\\\/x.com\\\/https:\\\/\\\/twitter.com\\\/OAziegbe\"],\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/author\\\/omozegie-aziegbe\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Upload Files With GraphQL in Java - Java Code Geeks","description":"Learn how to implement Java GraphQL upload file functionality in a Spring Boot API with comprehensive step-by-step guidance.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html","og_locale":"en_US","og_type":"article","og_title":"Upload Files With GraphQL in Java - Java Code Geeks","og_description":"Learn how to implement Java GraphQL upload file functionality in a Spring Boot API with comprehensive step-by-step guidance.","og_url":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html","og_site_name":"Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_author":"https:\/\/web.facebook.com\/omos.aziegbe","article_published_time":"2024-09-19T11:49:00+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2023\/06\/graphql-logo.jpg","type":"image\/jpeg"}],"author":"Omozegie Aziegbe","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/OAziegbe","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Omozegie Aziegbe","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html#article","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html"},"author":{"name":"Omozegie Aziegbe","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/7d3eac6e45542536e961129ae0fb453e"},"headline":"Upload Files With GraphQL in Java","datePublished":"2024-09-19T11:49:00+00:00","mainEntityOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html"},"wordCount":1096,"commentCount":0,"publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2023\/06\/graphql-logo.jpg","keywords":["GraphQL","Spring Boot"],"articleSection":["Enterprise Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html","url":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html","name":"Upload Files With GraphQL in Java - Java Code Geeks","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html#primaryimage"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2023\/06\/graphql-logo.jpg","datePublished":"2024-09-19T11:49:00+00:00","description":"Learn how to implement Java GraphQL upload file functionality in a Spring Boot API with comprehensive step-by-step guidance.","breadcrumb":{"@id":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html#primaryimage","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2023\/06\/graphql-logo.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2023\/06\/graphql-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.javacodegeeks.com\/upload-files-with-graphql-in-java.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java","item":"https:\/\/www.javacodegeeks.com\/category\/java"},{"@type":"ListItem","position":3,"name":"Enterprise Java","item":"https:\/\/www.javacodegeeks.com\/category\/java\/enterprise-java"},{"@type":"ListItem","position":4,"name":"Upload Files With GraphQL in Java"}]},{"@type":"WebSite","@id":"https:\/\/www.javacodegeeks.com\/#website","url":"https:\/\/www.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Developers Resource Center","publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/7d3eac6e45542536e961129ae0fb453e","name":"Omozegie Aziegbe","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2023\/12\/cropped-jcg_profile_pic-96x96.jpg","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2023\/12\/cropped-jcg_profile_pic-96x96.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2023\/12\/cropped-jcg_profile_pic-96x96.jpg","caption":"Omozegie Aziegbe"},"description":"Omos Aziegbe is a technical writer and web\/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.","sameAs":["https:\/\/web.facebook.com\/omos.aziegbe","https:\/\/www.linkedin.com\/in\/omosaziegbe\/","https:\/\/x.com\/https:\/\/twitter.com\/OAziegbe"],"url":"https:\/\/www.javacodegeeks.com\/author\/omozegie-aziegbe"}]}},"_links":{"self":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/126110","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/users\/128888"}],"replies":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=126110"}],"version-history":[{"count":0,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/126110\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media\/117826"}],"wp:attachment":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=126110"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=126110"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=126110"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}