如何使用正确的RequestBody.create方法使用Kotlin上传最新版本的图像? [英] how to upload image in latest retrofit version using Kotlin with the right RequestBody.create method?

查看:1236
本文介绍了如何使用正确的RequestBody.create方法使用Kotlin上传最新版本的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在此处或以下内容中阅读解决方案在这里,但是当我用自己的代码实现它时,我感到困惑

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

我正在使用我的gradle

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'

我正在尝试使用此代码在reiftift中上传图片

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>


}

并像这样使用它

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) {

    }

})

问题是,不赞成使用RequestBody.create

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

能请你帮我吗?

推荐答案

您可以像这样使用它:

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.

这篇关于如何使用正确的RequestBody.create方法使用Kotlin上传最新版本的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆