首页 > 解决方案 > 如何使用改造将图像发送到服务器

问题描述

我正在尝试使用改造、multipart/form-data 将图像发送到服务器。但我得到一个错误。

我试过用 Postman 发送图片,没问题。

@Multipart
@POST("requests/11006/history")
fun sendMessageWithImg(
    @Header("X-Device-UDID") deviceUDID: String = "",
    @Header("Authorization") token: String,
    @Part image: MultipartBody.Part
): Call<ResponseBody>


private fun upload(fileUri: Uri) {
    val tokenStorage = TokenStorage(this)
    val token = tokenStorage.getToken()
    val originalFile = FileUtils.getFile(this, fileUri)

    val filePart = RequestBody.create(
        MediaType.parse(contentResolver.getType(fileUri)),
        originalFile)

    val file: MultipartBody.Part = MultipartBody.Part.createFormData("image[]", originalFile.name, filePart)

    val client = ApiService.create()

    val call: Call<ResponseBody> = client
        .sendMessageWithImg(
            token = "Bearer $token",
            image = file)

    call.enqueue(object : Callback<ResponseBody>{

        override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
            print(call)
        }

        override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
            print(response)
        }

    })
}

错误是 - 无法从 /fec0::9c04 连接到.30::681c:587(端口 443)。(端口 38630)10000 毫秒后

标签: androidretrofitmultipartform-data

解决方案


试试这个代码

@Multipart
@POST("user/updateprofile")
Observable<ResponseBody> updateProfile(@Part("user_id") RequestBody id,
                                   @Part("full_name") RequestBody fullName,
                                   @Part MultipartBody.Part image,
                                   @Part("other") RequestBody other);



 //pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg");
RequestBody requestFile =
    RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
    MultipartBody.Part.createFormData("image", file.getName(), requestFile);

// add another part within the multipart request
 RequestBody fullName = 
    RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");

  service.updateProfile(id, fullName, body, other);

推荐阅读