POST Multipart Form Data using Retrofit 2.0 including image

前端 未结 10 1746
名媛妹妹
名媛妹妹 2020-11-22 11:07

I am trying to do a HTTP POST to server using Retrofit 2.0

MediaType MEDIA_TYPE_TEXT = MediaType.parse(\"text/plain\");
MediaType MEDIA_TYPE         


        
10条回答
  •  孤城傲影
    2020-11-22 11:49

    Kotlin version with update for deprication of RequestBody.create :

    Retrofit interface

    @Multipart
    @POST("uploadPhoto")
    fun uploadFile(@Part file: MultipartBody.Part): Call
    

    and to Upload

    fun uploadFile(fileUrl: String){
        val file = File(fileUrl)
        val fileUploadService = RetrofitClientInstance.retrofitInstance.create(FileUploadService::class.java)
        val requestBody = file.asRequestBody(file.extension.toMediaTypeOrNull())
        val filePart = MultipartBody.Part.createFormData(
            "blob",file.name,requestBody
        )
        val call = fileUploadService.uploadFile(filePart)
    
        call.enqueue(object: Callback{
            override fun onFailure(call: Call, t: Throwable) {
                Log.d(TAG,"Fckd")
            }
    
            override fun onResponse(call: Call, response: Response) {
                Log.d(TAG,"success"+response.toString()+" "+response.body().toString()+"  "+response.body()?.status)
            }
    
        })
    }
    

    Thanks to @jimmy0251

提交回复
热议问题