@@ -39,3 +39,101 @@ class UserRootValue(GraphQLView):
39
39
return request.user
40
40
41
41
```
42
+
43
+ ### File upload support
44
+
45
+ File uploads are supported via [ multipart requests] ( https://github.com/jaydenseric/graphql-multipart-request-spec ) .
46
+
47
+ You can simply define a `` FileUpload `` field in your schema, and use
48
+ it to receive data from uploaded files.
49
+
50
+
51
+ Example using `` graphql-core `` :
52
+
53
+ ``` python
54
+ from collections import NamedTuple
55
+ from graphql.type.definition import GraphQLScalarType
56
+
57
+
58
+ GraphQLFileUpload = GraphQLScalarType(
59
+ name = ' FileUpload' ,
60
+ description = ' File upload' ,
61
+ serialize = lambda x : None ,
62
+ parse_value = lambda value : value,
63
+ parse_literal = lambda node : None ,
64
+ )
65
+
66
+
67
+ FileEchoResult = namedtuple(' FileEchoResult' , ' data,name,type' )
68
+
69
+
70
+ FileEchoResultSchema = GraphQLObjectType(
71
+ name = ' FileEchoResult,
72
+ fields = {
73
+ ' data' : GraphQLField(GraphQLString),
74
+ ' name' : GraphQLField(GraphQLString),
75
+ ' type' : GraphQLField(GraphQLString),
76
+ }
77
+ )
78
+
79
+
80
+ def resolve_file_echo (obj , info , file ):
81
+ data = file .stream.read().decode()
82
+ return FileEchoResult(
83
+ data = data,
84
+ name = file .filename,
85
+ type = file .content_type)
86
+
87
+
88
+ MutationRootType = GraphQLObjectType(
89
+ name = ' MutationRoot' ,
90
+ fields = {
91
+ # ...
92
+ ' fileEcho' : GraphQLField(
93
+ type = FileUploadTestResultSchema,
94
+ args = {' file' : GraphQLArgument(GraphQLFileUpload)},
95
+ resolver = resolve_file_echo,
96
+ ),
97
+ # ...
98
+ }
99
+ )
100
+ ```
101
+
102
+
103
+ Example using `` graphene `` :
104
+
105
+ ``` python
106
+ import graphene
107
+
108
+ class FileUpload (graphene .Scalar ):
109
+
110
+ @ staticmethod
111
+ def serialize (value ):
112
+ return None
113
+
114
+ @ staticmethod
115
+ def parse_literal (node ):
116
+ return None
117
+
118
+ @ staticmethod
119
+ def parse_value (value ):
120
+ return value # IMPORTANT
121
+
122
+
123
+ class FileEcho (graphene .Mutation ):
124
+
125
+ class Arguments :
126
+ myfile = FileUpload(required = True )
127
+
128
+ ok = graphene.Boolean()
129
+ name = graphene.String()
130
+ data = graphene.String()
131
+ type = graphene.String()
132
+
133
+ def mutate (self , info , myfile ):
134
+ return FileEcho(
135
+ ok = True
136
+ name = myfile.filename
137
+ data = myfile.stream.read(),
138
+ type = myfile.content_type)
139
+ ```
0 commit comments