我在服务器端使用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需要额外的层来解析multipart请求,所以这可能不是我所需要的。 :
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 "
答案 0 :(得分:0)
我会自己回答。我拥有的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 -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'