File Upload🔗
In this section, we'll cover everything necessary for adding support for file uploads to your GraphQL schema using the GraphQL multipart request specification.
Setup🔗
Undine supports file uploads, but they are 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 request meets the criteria for
a "simple request".
Therefore, you should make sure CSRF protection is enabled on the GraphQL endpoint if you want to use file uploads. This can be done by making sure that
- The GraphQL view is decorated with
@csrf_protect, OR CsrfViewMiddlewareexists in yourMIDDLEWAREsetting (and the GraphQL view is not decorated with@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 and Image.
They correspond to Django's FileField and ImageField respectively.
The File scalar is for general files while the Image scalar validates that the file is an image file.
Like Django's
ImageField, using theImagescalar requires thePillowlibrary to be installed. You can install it together with Undine usingpip install undine[image].
Now, let's suppose you have the following Model.
If you add a create mutation to the GraphQL schema like this
...the TaskCreateMutation mutation InputObjectType will look like this:
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.
Reading file data🔗
By default, the File and Image scalars return the URL of the file. To return more
data about the file, use a TypedDict as the Field reference and add a custom resolver.
Only add data that is stored in the database or computed without the storage backend. For example,
FieldFile.sizeasks the storage backend for the file size. With a remote storage like S3, this is one request for every row in the result.
Image dimensions🔗
To return the width and height of an image, store them on the model with the width_field
and height_field arguments of ImageField. Django updates these fields when the image is
saved, and you can add them to the QueryType like other model fields.
Without these fields,
ImageFieldFile.widthandImageFieldFile.heightopen and read the image file for every row.