File Upload🔗
In this section, we'll cover the everything necessary for adding support for file uploads to your GraphQL schema using the GraphQL multipart request specification specification.
Setup🔗
Undine supports file uploads, but they disabled by default due to security reasons.
Specifically, since file uploads are sent using a multipart/form-data
request, they may be sent without
a CORS preflight request if the browser determines the requests meets the criteria for
a "simple request".
Therefore, you should make sure CSRF protection is enabled on the GraphQL endpoint.
This can be done by making sure that the GraphQL view has the @csrf_protect
decorator,
or that the CsrfViewMiddleware
exists in your MIDDLEWARE
setting (and the view is not using @csrf_exempt
).
Then you can enable file uploads by adding the following to your settings:
Uploading files🔗
Undine has two Scalars for uploading files: File
for uploading general files,
and Image
for uploading images. They correspond to Django's FileField
and ImageField
respectively.
The Image
scalar performs additional validations on the uploaded image,
such as checking if the uploaded file is an image file.
Like Django's
ImageField
, using theImage
scalar requires thePillow
library to be installed. You can install it together with Undine usingpip install undine[image]
.
Now, let's suppose we have the following model:
If we create a basic setup for creating a Task
:
Our GraphQL schema will have the following input object type:
Now the client can send a request that conforms to the GraphQL multipart request specification, and Undine's GraphQL view will parse the request and slot the files into the correct locations in the input data.
Example request
See the Implementations section in the GraphQL multipart request specification for client side libraries that support file uploads.