Uploading files
Apollo Kotlin supports file uploads via the GraphQL multipart request specification.
First, add the following custom scalar mapping to the Apollo Gradle plugin configuration:
build.gradle[.kts]
1
apollo
{
2
service
(
"service"
)
{
3
mapScalarToUpload
(
"Upload"
)
4
}
5
}
In this example, the GraphQL schema defines a custom scalar type named Upload
. You can use a different name as needed for your schema.
Note: You don’t need to register a type adapter for Upload
, because the mapScalarToUpload
method registers it automatically.
Now let’s consider a mutation that takes an Upload
as a parameter:
1
mutation
SingleUpload
(
$file
:
Upload
!
)
{
2
singleUpload
(
file
:
$file
)
{
3
id
4
path
5
filename
6
mimetype
7
}
8
}
Create an instance of Upload
using one of the factory methods:
1
2
val
upload
=
File
.
toUpload
(
"application/json"
)
3
4
5
val
upload
=
DefaultUpload
.
Builder
(
)
6
.
fileName
(
"filename.txt"
)
7
.
content
{
sink
->
8
okioSource
.
use
{
sink
.
writeAll
(
it
)
}
9
}
10
.
build
(
)
And execute your mutation:
1
val
response
=
apolloClient
.
mutation
(
SingleUploadMutation
(
file
=
upload
)
)
.
execute
(
)