如何使用 Retrofit 发送文件?

问题描述 投票:0回答:0

我试图使用 Retrofit 2 和 multipart/form-data 将图像发送到服务器,但出现错误“打开失败:ENOENT(没有这样的文件或目录)”。

这样向服务器发送文件是否正确,还是文件目录有问题?

@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()
        }
    }
}
kotlin android-jetpack-compose retrofit2
© www.soinside.com 2019 - 2024. All rights reserved.