问题
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