graphene
graphene copied to clipboard
Upload file
I'm currently attempting to upload files using Graphene and have explored several packages in my search. Unfortunately, none of them have proven effective. It seems to be a notable issue that Graphene lacks built-in support for file uploads.
Graphene does support file uploads, but it's a matter of the underlying web view (for example graphene Django, starlette-graphene3, GraphQL-server) to support them. What's your stack? If you're able to provide a minimal example I might be able to help.
In reality if you google this topic extensively, you'll notice that there are a number of ways to tackle it. In the example below, the path we've chosen is to stick to graphql only and used graphene-file-upload.
That graphene-file-upload package supports file transfers. By now, it seems that it hasn't received any updates in a couple of years. But if something would break, I can imagine it will be easy enough to fork and fix.
This very minimal example below is how I tackled the mutation a couple of years ago with that package. It's not intended to work out of the box, it's just a simplified snippet from a codebase in one of our projects at Tweave.tech
from graphene_file_upload.scalars import Upload
import graphene
from .validators import your_file_validator
class CreateFile(graphene.Mutation):
file = graphene.Field(FileType, required=False)
class Arguments:
filename = graphene.String(required=True)
filecontents = Upload(required=True)
@staticmethod
def mutate(root, info, filename, filecontents, *args, **kwargs):
user = info.context.user
file_instance = File()
file_instance.file.save(filename, ContentFile(filecontents.file.read()), save=False)
try:
your_file_validator(file_instance.file)
file_instance.save()
return CreateFile(file=file_instance)
except ValidationError:
return CreateFile(file=None)