【问题标题】:How should a GraphQL request for file upload look like?GraphQL 文件上传请求应该是什么样的?
【发布时间】:2019-04-03 08:03:54
【问题描述】:

我在服务器端使用Graphene,其代码与documentation中的代码相似:

class UploadFile(graphene.ClientIDMutation):
     class Input:
         pass
         # nothing needed for uploading file

     # your return fields
     success = graphene.String()

    @classmethod
    def mutate_and_get_payload(cls, root, info, **input):
        # When using it in Django, context will be the request
        files = info.context.FILES
        # Or, if used in Flask, context will be the flask global request
        # files = context.files

        # do something with files

        return UploadFile(success=True)

一切都清楚了,但是请求应该是什么样子?

我看到有人建议使用 multipart/form-data,但是 AFAIK 需要额外的层来解析多部分请求,所以这可能不是我需要的......或者是吗? :

curl -X "POST" "http://127.0.0.1:5001/graphql" \
     -H 'Content-Type: multipart/form-data; boundary=----GraphQLFileUpload' \
     -F "operations={\"query\":\"mutation ($files: [Upload!]!) {uploadFile(selfie: $file) {status}}\",\"variables\":{}}" \
     -F "map={\"x\":[\"variables.files.x\"]}" \
     -F "x=@/tmp/dummy.jpg "

【问题讨论】:

    标签: file-upload graphql graphene-python github-graphql


    【解决方案1】:

    我会自己回复。我的 curl 代码是基于一个外部库,这让我很困惑。

    这是我不需要任何额外库的解决方案:

    Python 服务器代码(石墨烯):

    class UploadImage(graphene.Mutation):
        class Arguments(object):
            file = graphene.String(required=True)
    
        status = graphene.Boolean()
    
        def mutate(self, info, file):
            img = info.context.files[file].read()
            # more stuff
            return UploadImage(status=True)
    

    Curl 请求(多部分形式)

    curl -X POST http://localhost:5001/graphql \
         -H 'content-type: multipart/form-data; boundary=----GraphQlFileUpload' \
         -F 'query=mutation {uploadImage(file: "photo") {status}}' \
         -F 'photo=@selfie.jpg'
    

    【讨论】:

    • ..但将文件作为 base64 字符串发送要容易得多。
    猜你喜欢
    • 1970-01-01
    • 2010-10-29
    • 2020-01-30
    • 2022-08-12
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多