'Upload image to GraphQL server

I'm using react-dropzone and graphql-server-express-upload to upload an image all in GraphQL Apollo. In my client the file looks like this: File on client

But in the server, when I log it, it looks like this:

{ preview: 'blob:http://localhost:3000/c622b0bd-3f0d-4f52-91f4-7676c8534c59' }

I'm following the instructions in the readme in graphql-server-express-upload, but no luck so far. How do I get the full image?



Solution 1:[1]

I ended up using apollo-upload-client, works great!

Solution 2:[2]

A different approach is to convert the binary image to BASE64 on the client side, before upload, then just populate the image as the BASE64 string on a GraphQLInputObjectType passed as an argument of a mutation. On the server the field can then simply be saved in a database column. For instance:

const UserInputType = new GraphQLInputObjectType({
  name: 'UserInput',
  description: 'The user of our system',

  fields: () => ({
    username: {
        type: GraphQLString,
        description: 'Name of the user'
    },
    image: {
        type: GraphQLString,
        description: 'Image of the user'
    }
  })
});

Solution 3:[3]

Here's an example using apollo-upload-client.

const UPLOAD_IMAGE = gql`
    mutation ($input: SetUploadImage!) {
        uploadImage(input: $input) {
            clientMutationId
        }
    }
`;

 const Photo = ({ id }) => {
     const [ mutate ] = useMutation(UPLOAD_IMAGE);
    
     function onChange({target: { validity, files: [file] }}) {
         if (validity.valid) {
             mutate({
                 variables: {
                     input: {
                         id,
                         params: {
                             image: file
                         }
                     }
                 }
             });
         }
      }
    
      return (
        <div css={style}>
          <input type="file" required onChange={onChange} />
        </div>
      )
}

Note that in order for this to work properly, you need to set the upload connect on the Apollo Client constructor.

const CLIENT = new ApolloClient({
  link: new createUploadLink({ ... })
  ...
});  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vlady Veselinov
Solution 2
Solution 3 Andrew