Upload Image from Apollo Client Android

Good afternoon, I need to know how I can upload an image from the Android gallery to my server. The file I get is Uri and I don’t know how to modify it to be able to upload it to the server.

I am using apollo client 3.

Thank you.

Hi! :wave:

The documentation for uploading files is here and should guide you on how to send files to your GraphQL server.

But first you will need to create an Upload object from the URI coming from the gallery. You can do this by getting an InputStream from the URI and then creating an Okio BufferedSource from it, by doing something like this:

        val parcelFileDescriptor = try {
            context.contentResolver.openFileDescriptor(mediaUri, "r")
        } catch (e: FileNotFoundException) {
            // Can't get a file descriptor, log / handle error
            null
        }
        if (parcelFileDescriptor == null) {
            // Can't get a file descriptor, log / handle error
            return
        }
        parcelFileDescriptor.use {
                val fileInputStream = FileInputStream(it.fileDescriptor)
                val bufferedSource = fileInputStream.source().buffer()
                val upload = DefaultUpload.Builder()
                      .content(bufferedSource)
                      .contentType(mimetype)
                      .build()
                // Now that you have an Upload object, use it in your mutation
                val response = apolloClient.mutation(YourUploadMutation(upload = upload)).execute()
        }

Note: I haven’t tested the code above but it should give you the general idea!

1 Like

Thank you very much for the information.