Search code examples
androidfile-uploadretrofit2multipart

Upload image using Retrofit2 (PATCH Request)


I know how to upload an image to server using POST request:

// AuthService.kt
@Multipart
@POST("auth/update")
fun updateInfo(
        @Header("Authorization") token: String,
        @Part("fullName") fullName: RequestBody,
        @Part("address") address: RequestBody,
        @Part avatarPic: MultipartBody.Part?
)

// Activity
val file = File(...
val reqFile = RequestBody.create(MediaType.parse("image/*"), file)
val avatarPic = MultipartBody.Part.createFormData("avatarPic", file.name, reqFile)
val fullName = RequestBody.create(MediaType.parse("text/plain"), "Saman")
val address = RequestBody.create(MediaType.parse("text/plain"), "Malekan")
authService.updateInfo(token, fullName, address, avatarPic)...

I want to send this request using PATCH method but I can't. I seems that it doesn't recognize fields. how can I achieve this?


Solution

  • I found the solution myself. I send the request via "Method Spoofing". I just changed the method in AuthService.kt to:

    @Multipart
    @POST("auth/update")
    fun updateInfo(
            @Header("Authorization") token: String,
            @Part("fullName") fullName: RequestBody,
            @Part("address") address: RequestBody,
            @Part avatarPic: MultipartBody.Part?,
            @Part("_method") method: RequestBody = RequestBody.create(MediaType.parse("text/plain"), "PATCH")
    )
    

    The _method field inside the request cause the server that act to request as PATCH request.