Search code examples
androidapollo-kotlin

Upload image to Graphql server using apollo kotlin


I need to upload image to my Graphql server from android application. The details in the documentation is not working. I need an example.


Solution

  • Came up with the solution. 1st I needed to create an upload scalar type. in Fragment class:

                    requireContext().contentResolver.openFileDescriptor(
                        selectedImageUri!!,
                        "r",
                        null
                    ) ?: return
                    
                    val file = File(
                        requireContext().cacheDir, requireContext().contentResolver.getFileName(
                            selectedImageUri
                        )
                    )
                    
                    val body = UploadRequestBody(file, "image")
                    
                    val upload = DefaultUpload.Builder()
                        .content(file)
                        .fileName(file.name)
                        .contentType(body.contentType().toString())
                        .build()
    

    In case what the UploadRequestBody class does:

    class UploadRequestBody(
      private val file: File,
      private val contentType: String
    ) : RequestBody() {
    
    override fun contentType() = "$contentType/*".toMediaTypeOrNull()
    
    override fun contentLength() = file.length()
    
    override fun writeTo(sink: BufferedSink) {
        val length = file.length()
        val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
        val fileInputStream = FileInputStream(file)
        var uploaded = 0L
        fileInputStream.use { inputStream ->
            var read: Int
            while (inputStream.read(buffer).also { read = it } != -1) {
                uploaded += read
                sink.write(buffer, 0, read)
            }
        }
    }
      companion object {
          private const val DEFAULT_BUFFER_SIZE = 2048
      }
    }