Retrofit 上传图片(单张)

服务器端返回信息的格式是:{"code":20000,"imgUrl":""}

编写interface——ApiUploadImg:

/**
 * 
 *上传图片接口
 */
public interface ApiUploadImg {
   /**图片上传API*/
  /*  @POST("Comm")
    Observable> uploadImg(@Body RequestApi RequestApi);*/

   @Multipart
   @POST("Comm/uploadImg")
   Call uploadImage(/*@Part("fileName") String description,*/
                            @Part("file\"; filename=\"image.png") RequestBody imgs);

//    @Multipart
//    @POST("Comm/uploadImg")
//    Observable> uploadImg( @Part("description") RequestBody description, @Part MultipartBody.Part file);

    @Multipart
    @POST("Comm/uploadImg")
    Call uploadImg( @Part("description") RequestBody description, @Part MultipartBody.Part file);
}
使用:

private void upLoadImg(String imgStr) {
        File file = new File(imgStr);
        // create RequestBody instance from file
        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("picture", file.getName(), requestFile);

        // add another part within the multipart request
        String descriptionString = "hello, this is description speaking";
        RequestBody description =
                RequestBody.create(
                        MediaType.parse("multipart/form-data"), descriptionString);

        // create upload service client
        ApiUploadImg service = RetrofitUtil.getInstance().getService(ApiUploadImg.class);

        // finally, execute the request
        Call call = service.uploadImg(description, body);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null != response) {
                    int code = response.body().getCode();
                    String imgUrl = response.body().getImgUrl();

                        switch (code) {
                            case 50000:
                                ToastUtil.toast(getMyActivity(), "上传图片偏成功");
                                break;
                            case 80020:
                                ToastUtil.toast(getMyActivity(), "上传图片失败,图片格式不正确");
                                break;
                            case 80021:
                                ToastUtil.toast(getMyActivity(), "上传图片失败,图片大小不正确");
                                break;
                        }
                        Log.e(TAG, "图片路径:" + imgUrl);


                } else {
                    ToastUtil.toast(getMyActivity(), getResources().getString(R.string.server_null));

                }

            }

            @Override
            public void onFailure(Call call, Throwable e) {
                ToastUtil.toast(getMyActivity(), getResources().getString(R.string.connect_server_error) + e.getMessage());

            }
        });

    }



你可能感兴趣的:(使用步骤)