Skip to content

GraphQL multipart uploads do not contain mimetype #385

Closed
@aalmazan

Description

@aalmazan

Describe the bug
Currently on v3.4.0 when uploading files, a mimetype is not being provided. This seems to default files as text/plain, at least on the Apollo GraphQL server implementation I've testing against.

The transport I'm currently using is requests, however, it's probably the case on other transports as well:

https://github.com/graphql-python/gql/blob/master/gql/transport/requests.py#L185-L187
https://github.com/graphql-python/gql/blob/master/gql/transport/aiohttp.py#L276-L278

Changing the following will work for my use case (requests transport):

# original
fields[k] = (getattr(v, "name", k), v)
# new 
fields[k] = (getattr(v, "name", k), v, 'application/pdf')
# or 
fields[k] = (getattr(v, "name", k), v, USER_PROVIDED_MIMETYPE)

To Reproduce
Same as above

Expected behavior

I suspect there's two ways about this:

  1. Autodetect the file's mimetype (or have an argument somewhere that allows the user to opt-in to this behavior):
import mimetypes
mimetype, _ = mimetypes.guess_type(file.name)
  1. Allow the user to provide the mimetype manually:
# Taken from the docs on uploading files: https://gql.readthedocs.io/en/stable/usage/file_upload.html
# Single file upload
with open("YOUR_FILE_PATH", "rb") as f:
    # old
    # params = {"file": f}
    # new
    params = {"file": (f, USER_DEFINED_MIMETYPE)}
    result = client.execute(
        query, variable_values=params, upload_files=True
    )


# Multi-file upload
f1 = open("YOUR_FILE_PATH_1", "rb")
f2 = open("YOUR_FILE_PATH_2", "rb")

params = {"files": [(f1, USER_DEFINED_MIMETYPE_1), (f2, USER_DEFINED_MIMETYPE_2)]}

System info (please complete the following information):

  • OS: Ubuntu
  • Python version: 3.9.12
  • gql version: 3.4.0
  • graphql-core version:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions