File Upload - WunderGraph
Overview
This feature is implemented according to the GraphQL multipart request specification, utilizing the multipart/form-data content type. Cosmo supports both single and multiple file uploads, but batch uploads are not supported. The router can be configured for file uploads with these options.
Multipart Request Structure
operations
A JSON-encoded operations object with files replaced by null. This object defines the GraphQL query or mutation to be executed, along with the necessary variables.
map
A JSON-encoded map indicating where files appear in the operations. For each file, the key is the file’s multipart form field name, and the value is an array of operations paths. This map ensures the correct association between the files and their respective variables in the GraphQL operation.
File Fields
Each file extracted from the operations object is assigned a unique, arbitrary field name. These fields are included in the multipart form data and correspond to the file paths specified in the map.
Sample Setup
Define Custom Scalar
You need to define a custom scalar Upload in your schema. This scalar will be used for the field type where you intend to upload files.
scalar Upload
type Mutation {
singleUpload(file: Upload!): Boolean!
multipleUpload(files: [Upload!]!): Boolean!
}
Single File Upload
To upload a single file, use the following curl command:
curl localhost:3002/graphql \
-F operations='{ "query": "mutation ($file: Upload!) { singleUpload(file: $file) }", "variables": { "file": null } }' \
-F map='{ "0": ["variables.file"] }' \
-F 0=@a.txt
This command sends a multipart request where:
operationsdefines the GraphQL mutation with thefilevariable set tonull.mapassociates the form field0withvariables.file.0=@a.txtuploads the filea.txtwith the form field name0.
Multiple Files Upload
To upload multiple files, use the following curl command:
curl localhost:3002/graphql \
-F operations='{ "query": "mutation($files: [Upload!]!) { multipleUpload(files: $files) }", "variables": { "files": [null, null] } }' \
-F map='{ "0": ["variables.files.0"], "1": ["variables.files.1"] }' \
-F 0=@a.txt \
-F 1=@b.txt
This command sends a multipart request where:
operationsdefines the GraphQL mutation with thefilesvariable set to an array ofnullvalues.mapassociates the form fields0and1withvariables.files.0andvariables.files.1respectively.0=@a.txtand1=@b.txtupload the filesa.txtandb.txtwith form field names0and1.
By following these examples, you can configure your router to handle single and multiple file uploads effectively using GraphQL multipart requests. For more details, refer to the GraphQL multipart request specification.