【问题标题】:How to upload image to server with Retrofit on Android如何在 Android 上使用 Retrofit 将图像上传到服务器
【发布时间】:2021-03-18 18:27:32
【问题描述】:

在我的应用程序中,我应该将图像上传到服务器。
对于服务器请求,我使用 retrofit 2
我编写了上传代码,但显示验证错误并说我的媒体字段为空

PostMan 上传图片请求:Click to see image

在邮递员中一切正常,没有任何问题,图片上传成功!

但在我的代码中显示验证错误!

我的api接口代码:

@Multipart
@POST("media/")
fun uploadImage(
    @Header(AUTHORIZATION) auth: String, @Header(ACCEPT) accept: String, @Header(CONTENT_TYPE) contentType: String,
    @Part media: MultipartBody.Part
): Single<Response<ResponseModelUploadImage>>

上传图片代码:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    photoEasy.onActivityResult(
        requestCode, resultCode
    ) { thumbnail ->
        val imgFile = bitmapToFile(thumbnail, "myImageNameIsThisTest.jpeg")
        Log.e("filePath",imgFile.toString())
        val reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), imgFile)
        val filePart = MultipartBody.Part.createFormData("media", imgFile?.name, reqFile)

        presenter.callUploadImage(userToken, APPLICATION_JSON, APPLICATION_JSON, filePart)
    }
}

我该如何解决?

URL

【问题讨论】:

    标签: android kotlin retrofit retrofit2


    【解决方案1】:

    这是一个 Android 应用程序(在 Kotlin 中)中的上传功能示例,该应用程序将图片发送到服务器(在本例中是使用 Java 和 Spring Boot 开发的 Web 应用程序),Retrofit 为 多部分/表单数据

     private suspend fun sendPicture(sessionId: UUID, p: Picture): Boolean {
    
            try {
                val data_part = p.data.toRequestBody("multipart/form-data".toMediaTypeOrNull())
                val data_multi_part =
                    MultipartBody.Part.createFormData("picture", p.description, data_part)
                val sessionId_part =
                    sessionId.toString().toRequestBody("multipart/form-data".toMediaTypeOrNull())
                val id_part = p.id.toString().toRequestBody("multipart/form-data".toMediaTypeOrNull())
                val categoryId_part =
                    p.categoryId?.toString()?.toRequestBody("multipart/form-data".toMediaTypeOrNull())
                val response = api.sendPicture(sessionId_part, id_part, categoryId_part, data_multi_part)
                if (!response.isSuccessful) {
    
                    @Suppress("BlockingMethodInNonBlockingContext")
                    val msg = response.errorBody()?.string() ?: textHelper(
                        R.string.error_send_picture,
                        p.id.toString()
                    )
                    Logger.trace(EventCode.SerializationError, msg, EventSeverity.Error)
                }
                return response.isSuccessful
    
            } catch (e: Exception) {
    
                Logger.trace(p, EventCode.SerializationError, e.localizedMessage, Action.Send, EventSeverity.Exception)
            }
    
            return false
        }
    

    并且使用Retrofit 2.6生成的API声明如下:

        @Multipart
        @POST("SendPicture")
        suspend fun sendPicture(@Part("sessionId") sessionId: RequestBody, @Part("pictureId") id: RequestBody, @Part("categoryId") categoryId: RequestBody?, @Part picture: MultipartBody.Part): Response<Void>
    

    考虑到Picture 是一个 Android Room (ORM) 实体,p.data 是作为字节数组 (val data: ByteArray) 的图像表示。

    sessionId = is a session ID (it's just a custom value of type UUID)
    pictureId = is the ID of the picture (type: UUID)
    categoryId = is the ID of the category the picture belongs to (type: UUID)
    

    这 3 个值是自定义的(您不需要它们),它们只是为了展示如何将更多数据与图像一起传递到服务器。

    函数是用 Kotlin 编写的。

    我认为您拥有提取更适合您需求的代码所需的一切。这个例子取自我的一个项目的代码,并经过测试。它将存储在本地数据库中的图片发送到服务器。

    您可以轻松地将代码移植到 Java。

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 2015-01-02
      • 2023-03-12
      • 1970-01-01
      • 2013-12-17
      • 2014-03-21
      • 2014-03-24
      • 2011-09-19
      相关资源
      最近更新 更多