0

I was trying to send an image to the server using Retrofit 2 and multipart/form-data but getting error "open failed: ENOENT (No such file or directory)".

Is it correct to send files to the server like this, or is the problem in the file directory?

@Headers(
"accept: */*",
"Content-Type: multipart/form-data"
)
@Multipart
@POST("avatar")
suspend fun updateAvatar(@Header("Authorization") auth: String, @Part("file") userImage: RequestBody): Response<JsonObject>

fun updateProfile(
    firstName: String,
    patronymic: String,
    lastName: String,
    birthday: String,
    gender: String,
    userAvatar: String,
    userToken: String
) {
    message.value = null
    sendEmailResponseCode.value = null
    checkEmailResponseCode.value = null
    createCardResponseCode.value = null

    viewModelScope.launch {
        val apiService = ApiService.getInstance()
        try {
            val json = apiService.updateProfile(
                "Bearer ${userToken.replace("\"", "")}",
                mapOf(
                    "firstname" to firstName,
                    "lastname" to lastName,
                    "patronymic" to patronymic,
                    "birthday" to birthday,
                    "gender" to gender
                )
            )

            val file = File(userAvatar)

            val multipartBody = file.asRequestBody("image/*".toMediaType())

            if (json.code() == 200) {
                val avatarJson = apiService.updateAvatar("Bearer ${userToken.replace("\"", "")}", multipartBody)

                Log.d("LOG", "updateProfile: $avatarJson")
            }
            else if (json.code() == 403) {
                message.value = "No Auth."
            }
            else {
                message.value = json.code().toString()
            }

            createCardResponseCode.value = json.code()
        }
        catch (e: Exception) {
            Log.d("ERROR", "updateProfile: $e")
            message.value = e.message.toString()
        }
    }
}
m0skit0
  • 25,268
  • 11
  • 79
  • 127
TriangleN
  • 167
  • 1
  • 1
  • 7

0 Answers0