retrofit上传图片

  • 上传图片的格式:multipart/form-data

  • 因此接口一定得加上这个 @Multipart 注解

interface IFileApi{

    @Multipart
    @POST("/api/*****/{id}/image")
    fun uploadImgFile(@Path("id")id: Int,
                      @Part requestBody: MultipartBody.Part):
            Observable<RespFileModel>

}


  • fileUpload 的presenter如下:

 override fun upload(id: Int, file: File) {

        val requestFile: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
        val body: MultipartBody.Part = MultipartBody.Part.createFormData("image", file.name, requestFile)


        MyRetrofit.getClient().create(IFileApi::class.java)
                .uploadImgFile(id, body)
                .compose(RxUtil.io_main())
                .doOnSubscribe {
                    compositeDisposable.add(it)
                }
                .subscribe({
                    if (HttpCodeCheck.success(it.code)) {
                        mViewReference.get()?.uploadSuccess()
                    } else {
                        mViewReference.get()?.uploadFailed(ApiException(it.code, it.message))
                    }
                }, {
                    mViewReference.get()?.uploadFailed(it)
                })
    }

  • 这样便可实现上传图片

你可能感兴趣的:(android)