Apollo GraphQL File Upload Link

19.0.0 · active · verified Tue Apr 21

apollo-upload-client is a terminating Apollo Link for Apollo Client that facilitates file uploads within GraphQL mutations using the GraphQL multipart request specification. It automatically detects `FileList`, `File`, or `Blob` instances in GraphQL variables and constructs a multipart request, falling back to a standard GraphQL POST or GET request otherwise. The current stable version is 19.0.0, with major versions released somewhat frequently to align with `@apollo/client` updates and Node.js LTS changes. Its primary differentiator is seamless integration with Apollo Client for file uploads, abstracting the multipart request complexity, and adhering to the community-standard GraphQL multipart request specification. It requires a compatible server-side implementation that also follows the specification.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `apollo-upload-client` with Apollo Client, define a GraphQL mutation for file uploads, and use it within a React component. It initializes `createUploadLink` with a GraphQL endpoint and wraps a file input with a `useMutation` hook to send the selected file to the server.

import { ApolloClient, InMemoryCache, gql, ApolloProvider } from '@apollo/client';
import { createUploadLink } from 'apollo-upload-client';
import React from 'react';
import { useMutation } from '@apollo/client/react';

// Configure the Apollo Client with the upload link
const uploadLink = createUploadLink({
  uri: 'http://localhost:4000/graphql', // Replace with your GraphQL server endpoint
});

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: uploadLink,
});

// GraphQL mutation definition for file upload
const UPLOAD_FILE_MUTATION = gql`
  mutation uploadFile($file: Upload!) {
    uploadFile(file: $file) {
      filename
      mimetype
      encoding
      success
    }
  }
`;

/** React component for uploading a single file. */
function UploadFileComponent() {
  const [uploadFile, { loading, error, data }] = useMutation(UPLOAD_FILE_MUTATION);

  const handleFileChange = ({ target: { validity, files } }) => {
    if (validity.valid && files && files[0]) {
      uploadFile({
        variables: {
          file: files[0],
        },
      });
    }
  };

  return (
    <div>
      <input type="file" required onChange={handleFileChange} />
      {loading && <p>Uploading...</p>}
      {error && <p>Error: {error.message}</p>}
      {data && <p>Upload successful: {data.uploadFile.filename}</p>}
    </div>
  );
}

// Root component to provide Apollo Client context
function App() {
  return (
    <ApolloProvider client={client}>
      <h1>File Upload Example</h1>
      <UploadFileComponent />
    </ApolloProvider>
  );
}

export default App;

view raw JSON →