0

How to post to an api like this using retrofit

I am trying to create a simple app where I can post the file to the given Api. I have created the retrofit interface and the instance of it and got the file uri. I've tried methods of creating a file from getting the path from uri but the it doesn't work on new sdk versions.

Here's my Retrofit interface:

interface RetrofitApi {

    @Multipart
    @POST("UploadFile")
    suspend fun postFile(@Part type: MultipartBody.Part, @Part file: MultipartBody.Part) : Call<RequestBody>
}

Here's my RetrofitHelper object:

object RetrofitHelper {
    val baseUrl = "MY_URL"

    fun getInstance(): Retrofit {
        return Retrofit.Builder().baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            // we need to add converter factory to
            // convert JSON object to Java object
            .build()
    }
}

Here's my code for file selection:

class MainActivity : AppCompatActivity() {

    lateinit var selectFile: Button
    private val TAG: String = "ReposeMainActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        selectFile = findViewById(R.id.select_file)
        selectFile.setOnClickListener{
            openFileDialog(it)
        }

    }

    var sActivityLauncher = registerForActivityResult(
        StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK) {
            val data = result.data
            val uri = data!!.data
//            val inputStream: InputStream? = contentResolver.openInputStream(uri!!)
            val file = File(uri!!.path)

            lifecycleScope.launch{
//                upload();
                uploadFile(file)
            }

            Log.d(TAG, "Uri : $uri File : $file ")
        }
    }

    private fun uploadFile(file: File) {
        TODO("Not yet implemented")
    }


    private fun openFileDialog(view: View) {
        var data = Intent(Intent.ACTION_OPEN_DOCUMENT)
        data.type = "*/*"
        data = Intent.createChooser(data, "Choose a file")
        sActivityLauncher.launch(data)
    }
}

How do I proceed with the uploadFile function in the MainActivity? Please point out the mistakes I made here, if any, and guide me to proceed with uploading

  • you can give this try [Upload file in Android Java with retrofit 2](https://thanhtungvo.medium.com/upload-file-in-android-jave-with-retrofit-2-ae4822224e94) – Vishal Beep May 01 '22 at 07:37

0 Answers0