You are viewing documentation for a previous version of this software.

Switch to the latest stable version.

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:

Kotlin
build.gradle[.kts]
1apollo {
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:

GraphQL
1mutation 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:

Kotlin
1// If you're on Android/JVM, you can turn a File into an upload
2val upload = File.toUpload("application/json")
3
4// On multiplatform, you can use `DefaultUpload`
5val upload = DefaultUpload.Builder()
6              .fileName("filename.txt")
7              .content { sink ->
8                okioSource.use { sink.writeAll(it) }
9              }
10              .build()

And execute your mutation:

Kotlin
1val response = apolloClient.mutation(SingleUploadMutation(file = upload)).execute()
Feedback

Edit on GitHub

Forums