使用改造将图像上传到服务器

时间:2019-03-01 09:09:13

标签: android retrofit

我正在尝试使用Retrofit2将图像上传到服务器。我认为我发送数据的方式不正确,但是我还没有弄清楚问题出在哪里。

我应该以以下格式发送数据:{"file": image, "userID": userId}

这是我在改造界面中的代码:@POST("avatar") fun uploadImage(@Body data: Data ) : Call<ResponseBody>

我用文件和用户ID创建了一个对象数据,我不知道这是否正确。我也看到了这个例子

ublic interface UploadAPIs {
@Multipart
@POST("/upload")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part file, @Part("name") RequestBody requestBody);

}

但是我真的不太了解,我怎么能感觉到一个多部分的物体

这是我创建从片段中的图库中获取的图像文件的方式

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

    if (resultCode == Activity.RESULT_OK)

        when(requestCode){
            GALLERY -> {
                val selectedImage= data!!.data

                val file = File(selectedImage.path)

                val data = Data(file, userID)

                val call = api!!.uploadImage(data)

                call.enqueue(object: Callback<ResponseBody>{
                    override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                        Toast.makeText(context, t.message, Toast.LENGTH_SHORT).show()
                    }

                    override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                        val response = response.body()!!.string()
                        println("Response " + response)

                        //response says user does not exist because the way I send data is not correct
                    }

                })

            }

            CAMERA -> {
             //code here
            }
        }

}

这是我为数据对象创建的类<​​/ p>

class Data (val file: File, userID: Int)

如果有人可以帮助我,我将不胜感激:)

更新的代码:

@Multipart
@POST("avatar")
fun uploadImage(
        @Part("userID") user_ID: RequestBody,
        @Part image: MultipartBody.Part) : Call<ResponseBody>


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

    if (resultCode == Activity.RESULT_OK)

        when(requestCode){
            GALLERY -> {
                val selectedImage= data!!.data

                val bitmap = MediaStore.Images.Media.getBitmap(context!!.contentResolver, selectedImage)
                avatar.setImageBitmap(bitmap)

                val file = File(getRealPathFromURI(selectedImage))


                val id = RequestBody.create(MediaType.parse("text/plain"), userID.toString())

                //val reqBody = RequestBody.create(MediaType.parse(activity!!.contentResolver.getType(selectedImage)!!), file)

                val reqBody = RequestBody.create(MediaType.parse("image/*"), file)

                val body = MultipartBody.Part.createFormData("file", file.name, reqBody)

                val call = api!!.uploadImage(id, body)

                call.enqueue(object: Callback<ResponseBody>{
                    override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                        Toast.makeText(context, t.message, Toast.LENGTH_SHORT).show()
                        println("Failure")
                    }

                    override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                        if (response.isSuccessful){
                            println("Successful " + response.body()?.string())

                        }else{
                            response.errorBody()?.string()
                            println("Error " + response.headers().toString())

                        }


                    }

                })

            }

            CAMERA -> {
               //code
            }
        }

}

1 个答案:

答案 0 :(得分:0)

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

    if (resultCode == Activity.RESULT_OK)

        when(requestCode){
            GALLERY -> {
                val selectedImage= data!!.data

                val bitmap = MediaStore.Images.Media.getBitmap(context!!.contentResolver, selectedImage)
                avatar.setImageBitmap(bitmap)

                val file = File(getRealPathFromURI(selectedImage))

                val id = RequestBody.create(MediaType.parse("text/plain"), userID.toString())

                val reqBody = RequestBody.create(MediaType.parse("image/jpeg"), file)

                val body = MultipartBody.Part.createFormData("file", file.name, reqBody)

                val api = RetrofitClient.getInstance().apiService
                val call = api!!.uploadImage(id, body)

                call.enqueue(object: Callback<ResponseBody>{
                    override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                        Toast.makeText(context, t.message, Toast.LENGTH_SHORT).show()
                        println("Failure")
                    }

                    override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                        if (response.isSuccessful){
                            println("Successful " + response.body()?.string())

                        }else{
                            response.errorBody()?.string()
                            println("Error " + response.headers().toString())

                        }


                    }

                })


            }

            CAMERA -> {
                //code here
            }
        }

}

并在API接口中:

@Multipart
@POST("avatar")
fun uploadImage(
        @Part("userID") user_ID: RequestBody,
        /*@Part("file") name: RequestBody*/
        @Part image: MultipartBody.Part) : Call<ResponseBody>