how to upload image in latest retrofit version using Kotlin with the right RequestBody.create method?

江枫思渺然 提交于 2021-01-07 06:59:06

问题


I have tried to read the solution in here or in here , but I am confused when I implement it on my own code

I am using this on my gradle

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0'

I am trying to upload an image using this code in retorift

interface UploadMediaAPI {

    @Multipart
    @POST("uploadImage")
    fun uploadImage(
        @Part image: MultipartBody.Part
    ): Call<UploadResponse>


}

and use it like this

val fileImagePart = MultipartBody.Part.createFormData("imageFile", file.name, RequestBody.create("image/*".toMediaTypeOrNull(), file))
val call = uploadMediaAPI.uploadImage(image = fileImagePart)

call.enqueue(object : Callback<UploadResponse> {


    override fun onResponse(call: Call<UploadResponse>, response: Response<UploadResponse>) {

    }

    override fun onFailure(call: Call<UploadResponse>, t: Throwable) {

    }

})

the problem is, the RequestBody.create is deprecated

it is said in here , I have to use the code below to change the deprecated method

val file = File("path")
file.asRequestBody("image/jpeg".toMediaTypeOrNull())

but I am really confused how to put this code in my own code

could you please help me ?


回答1:


You can use it like this:

val file = File(FileUtil.getPath(this, <your_uri>)) // get file from uri
val requestFile = file.asRequestBody(contentResolver.getType(<your_uri>)?.toMediaTypeOrNull())
val body = MultipartBody.Part.createFormData("imageFile", file.name, requestFile)
val call = uploadMediaAPI.uploadImage(image = body)

call.enqueue(object: Callback<UploadResponse> {

  override fun onResponse(call: Call<UploadResponse>, response: Response<UploadResponse>) {
  }

  override fun onFailure(call: Call<UploadResponse>, t: Throwable) {
  }
})

For more information please check here.



来源:https://stackoverflow.com/questions/64744692/how-to-upload-image-in-latest-retrofit-version-using-kotlin-with-the-right-reque

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!