I'm currently using graphene-django v2.0 and I've absolutely no clue of how can I upload and download files like images, does anyone have an example of a query where you can download an Image and a mutation where you can upload one?

- 21,866
- 6
- 108
- 99

- 421
- 5
- 13
-
2There is a package called graphene-file-upload, github: https://github.com/lmcgartland/graphene-file-upload which should do the work for you. I have not been able to make it work yet, but give it a try. It could be useful with a working implementation example. – William Jul 11 '18 at 19:32
1 Answers
UPLOADS
You don't need to invent your own frontend code to add a file upload to a mutation -- there are existing packages that do this already. For example, apollo-upload-client if you are using Apollo.
To receive an uploaded file on the backend, the files are going to be available in the dictionary request.FILES
. So any mutation handling a file upload needs to examine info.context.FILES.items
to get and save the file data. The specifics of this code are going to depend on the ultimate destination of the saved file.
(UPDATE) However, if possible I would recommend not using graphene-django to upload files because it adds a large amount of complexity on both the backend and the frontend. My team ultimately scrapped our working graphene-django file upload code and replaced it with a standard Django file upload.
DOWNLOADS
For downloads, I would recommend not using graphQL for the actual download. Instead create a Django function view that returns a HttpResponse
or FileResponse
and sets the Content-Disposition header. Something like
from django.http import HttpResponse
def download(request):
... do stuff to get file contents and file name and mime_type
response = HttpResponse(file_contents, content_type=mime_type)
response['Content-Disposition'] = 'attachment; filename="{}"'.format(file_name)
return response
Then add this download path to your urls.py
and to a graphQL query response. So graphQL would be used to get the download path, but actually downloading the file would be a regular Django page.

- 21,866
- 6
- 108
- 99
-
Can you elaborate on your last two sentences? I'm not sure how graphQL and `urls.py` interact together at all... – Ren Nov 13 '19 at 16:44
-
In this case, I'm talking about a normal Django flow that doesn't use graphQL -- so you'd edit urls.py to route to the download view in the normal Django way. – Mark Chackerian Nov 13 '19 at 17:45
-
1Thanks, I think I am starting to figure it out :D By the way, how do you pass the address in the query? in my work, we have different environments (local-api.address.com/8000, test-api.address.com, api.address.com, etc), do you know how to get the right one from django? – Ren Nov 13 '19 at 19:16