user3431327
user3431327

Reputation: 155

Graphql upload getting "Invalid JSON in the ‘operations’ multipart field"

I been struggling to figure out how to get file upload working in graphql.

Here is basic implementation i have.


// eslint-disable-next-line import/no-extraneous-dependencies
const { ApolloServer, gql }             = require('apollo-server-express')
// eslint-disable-next-line import/no-extraneous-dependencies
const express                      = require('express')


const typeDefs = gql`  
  type File {
    filename: String!
    mimetype: String!
    encoding: String!
  }
  
  type Query {
    _ : Boolean
  }
  
  type Mutation {
    singleUpload(file: Upload!): File!,
    singleUploadStream(file: Upload!): File!
  }
`;

const resolvers = {
  Mutation: {
    singleUpload: (parent, args) => {
      return args.file.then(file => {
        const {createReadStream, filename, mimetype} = file

        const fileStream = createReadStream()

        return file;
      });
    },
    singleUploadStream: async (parent, args) => {
      const file = await args.file
      const {createReadStream, filename, mimetype} = file
      const fileStream = createReadStream()

      const uploadParams = {Bucket: 'apollo-file-upload-test', Key: filename, Body: fileStream};

      console.log(result)


      return file;
    }
  },
};


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

const app = express()
server.applyMiddleware({ app })

const port = Number(process.env.API_PORT || 4000)

app.listen({ port }, () => {
    // eslint-disable-next-line no-console
    console.debug(`🚀 Server ready at http://localhost:${port}${server.graphqlPath}`)
})

i am follow the doc for graphql-upload library. https://github.com/jaydenseric/graphql-multipart-request-spec

This is the command i'm using to upalod:

curl http://localhost:4000/graphql -F operations='{ "query": "mutation ($file: Upload!) { singleUploadStream
(file: $file) { filename } }”, "variables": { "file": null } }' -F map='{ "0": ["variables.file"] }' -F 0=@/Users/XXX/Downloads/image.jpg

Upvotes: 3

Views: 4480

Answers (1)

Jayden Seric
Jayden Seric

Reputation: 81

There error message is exactly right, the JSON in the operations field in the multipart request is invalid. Here is the JSON you are attempting to use:

{ "query": "mutation ($file: Upload!) { singleUploadStream
(file: $file) { filename } }”, "variables": { "file": null } }

Firstly, newlines should be avoided or escaped using \n in JSON:

 { "query": "mutation ($file: Upload!) { singleUploadStream(file: $file) { filename } }”, "variables": { "file": null } }

Secondly, you’re using a typographic end quote character instead of the correct double quote character " for the query value:

 { "query": "mutation ($file: Upload!) { singleUploadStream(file: $file) { filename } }", "variables": { "file": null } }

Upvotes: 6

Related Questions