Graphql 上传获取“‘操作’多部分字段中的 JSON 无效”

use*_*327 2 javascript graphql-js apollo-server

我一直在努力弄清楚如何让文件上传在 graphql 中工作。

\n

这是我的基本实现。

\n
\n// eslint-disable-next-line import/no-extraneous-dependencies\nconst { ApolloServer, gql }             = require(\'apollo-server-express\')\n// eslint-disable-next-line import/no-extraneous-dependencies\nconst express                      = require(\'express\')\n\n\nconst typeDefs = gql`  \n  type File {\n    filename: String!\n    mimetype: String!\n    encoding: String!\n  }\n  \n  type Query {\n    _ : Boolean\n  }\n  \n  type Mutation {\n    singleUpload(file: Upload!): File!,\n    singleUploadStream(file: Upload!): File!\n  }\n`;\n\nconst resolvers = {\n  Mutation: {\n    singleUpload: (parent, args) => {\n      return args.file.then(file => {\n        const {createReadStream, filename, mimetype} = file\n\n        const fileStream = createReadStream()\n\n        return file;\n      });\n    },\n    singleUploadStream: async (parent, args) => {\n      const file = await args.file\n      const {createReadStream, filename, mimetype} = file\n      const fileStream = createReadStream()\n\n      const uploadParams = {Bucket: \'apollo-file-upload-test\', Key: filename, Body: fileStream};\n\n      console.log(result)\n\n\n      return file;\n    }\n  },\n};\n\n\nconst server = new ApolloServer({ typeDefs, resolvers });\n\nconst app = express()\nserver.applyMiddleware({ app })\n\nconst port = Number(process.env.API_PORT || 4000)\n\napp.listen({ port }, () => {\n    // eslint-disable-next-line no-console\n    console.debug(` Server ready at http://localhost:${port}${server.graphqlPath}`)\n})\n
Run Code Online (Sandbox Code Playgroud)\n

我正在遵循 graphql-upload 库的文档。\n https://github.com/jaydenseric/graphql-multipart-request-spec

\n

这是我用来上传的命令:

\n
curl http://localhost:4000/graphql -F operations=\'{ "query": "mutation ($file: Upload!) { singleUploadStream\n(file: $file) { filename } }\xe2\x80\x9d, "variables": { "file": null } }\' -F map=\'{ "0": ["variables.file"] }\' -F 0=@/Users/XXX/Downloads/image.jpg\n
Run Code Online (Sandbox Code Playgroud)\n

小智 6

错误消息完全正确,operations多部分请求中字段中的 JSON 无效。这是您尝试使用的 JSON:

\n
{ "query": "mutation ($file: Upload!) { singleUploadStream\n(file: $file) { filename } }\xe2\x80\x9d, "variables": { "file": null } }\n
Run Code Online (Sandbox Code Playgroud)\n

\\n首先,在 JSON 中应避免或转义换行符:

\n
 { "query": "mutation ($file: Upload!) { singleUploadStream(file: $file) { filename } }\xe2\x80\x9d, "variables": { "file": null } }\n
Run Code Online (Sandbox Code Playgroud)\n

其次,您\xe2\x80\x99 使用印刷结束引号字符\xe2\x80\x9d而不是"query值的正确双引号字符:

\n
 { "query": "mutation ($file: Upload!) { singleUploadStream(file: $file) { filename } }", "variables": { "file": null } }\n
Run Code Online (Sandbox Code Playgroud)\n