0
0
GraphqlHow-ToBeginner · 4 min read

How to Upload File in GraphQL: Syntax and Example

To upload a file in GraphQL, use the graphql-upload specification which supports multipart requests. Define a mutation that accepts an Upload scalar type, then send the file using a multipart form request from the client.
📐

Syntax

File upload in GraphQL uses a special Upload scalar type in a mutation. The client sends a multipart/form-data request where the file is attached. The server processes the file stream inside the resolver.

  • mutation: Defines the operation to upload the file.
  • file: Upload! The file input parameter with the Upload scalar type.
  • graphql-upload: Middleware or library to handle multipart requests.
graphql
mutation UploadFile($file: Upload!) {
  uploadFile(file: $file) {
    filename
    mimetype
    encoding
  }
}
💻

Example

This example shows a simple GraphQL server using graphql-upload in Node.js and a client mutation to upload a file.

javascript
// Server setup (Node.js with Apollo Server)
const { ApolloServer, gql } = require('apollo-server');
const { GraphQLUpload } = require('graphql-upload');

const typeDefs = gql`
  scalar Upload

  type File {
    filename: String!
    mimetype: String!
    encoding: String!
  }

  type Mutation {
    uploadFile(file: Upload!): File!
  }
`;

const resolvers = {
  Upload: GraphQLUpload,
  Mutation: {
    uploadFile: async (_, { file }) => {
      const { filename, mimetype, encoding, createReadStream } = await file;
      // Here you can save the file stream to disk or cloud
      const stream = createReadStream();
      // For demo, we just consume the stream without saving
      stream.on('data', () => {});
      stream.on('end', () => {});
      return { filename, mimetype, encoding };
    },
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

// Client mutation example (using Apollo Client or fetch)
// mutation UploadFile($file: Upload!) {
//   uploadFile(file: $file) {
//     filename
//     mimetype
//     encoding
//   }
// }
Output
Server ready at http://localhost:4000/
⚠️

Common Pitfalls

  • Not using multipart/form-data on the client causes the file not to upload.
  • Missing Upload scalar type in the schema leads to errors.
  • Not using middleware like graphql-upload on the server prevents file parsing.
  • Trying to upload files in GET requests instead of POST.
graphql
/* Wrong: Missing Upload scalar and middleware */
const typeDefs = gql`
  type Mutation {
    uploadFile(file: String!): Boolean
  }
`;

/* Right: Include Upload scalar and middleware */
const { GraphQLUpload } = require('graphql-upload');
const typeDefs = gql`
  scalar Upload
  type Mutation {
    uploadFile(file: Upload!): Boolean
  }
`;
📊

Quick Reference

StepDescription
Define Upload scalarAdd scalar Upload in your schema.
Create mutationAdd a mutation that accepts file: Upload!.
Use graphql-upload middlewareEnable multipart request parsing on server.
Send multipart requestClient sends file using multipart/form-data.
Handle file streamResolver processes the file stream for saving.

Key Takeaways

Use the Upload scalar type in your GraphQL schema to accept files.
Enable multipart/form-data handling on the server with graphql-upload middleware.
Send files from the client as multipart requests, not as plain JSON.
Process the file stream in the resolver to save or use the uploaded file.
Avoid missing Upload scalar or middleware to prevent upload failures.