Retrofit 2.0.2 image upload using multipart

2019-02-27 18:03发布

问题:

I am new for Retrofit I wanna to upload single image with different params like name,dob,mobile. i don't know where i am wrong Please guide me. I follow this LINK

Here is my code

interface

 @Multipart
    @POST("signup")
    Call<ResponseBody> getSignup(@Part("name") RequestBody name, @Part("email") RequestBody email, @Part("dob") RequestBody dob, @Part("phone") RequestBody phone, @Part("IMEI") RequestBody IMEI, @Part MultipartBody.Part file);

upload code

 // 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("image", file.getName(), requestFile);

                RequestBody name =
                        RequestBody.create(
                                MediaType.parse("multipart/form-data"), et_name.getText().toString());

                RequestBody email =
                        RequestBody.create(
                                MediaType.parse("multipart/form-data"), et_email.getText().toString());

                RequestBody dob =
                        RequestBody.create(
                                MediaType.parse("multipart/form-data"), et_dob.getText().toString());

                RequestBody mobile =
                        RequestBody.create(
                                MediaType.parse("multipart/form-data"), et_mobile.getText().toString());


                RequestBody imei =
                        RequestBody.create(
                                MediaType.parse("multipart/form-data"), IMEI);

                Call<ResponseBody> responseBodyCall = apiInterface.getSignup(name, email, dob, mobile, imei, body);
                responseBodyCall.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                        String response_two = response.body().toString();

                        Log.i(TAG, "onResponse: " + response_two);
//                        startActivity(new Intent(this, OTPActivity.class));
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.e("Upload error:", t.getMessage());
                    }
                });

回答1:

its my example of POST multipart

@Multipart
@POST("/api/register?platform=android")
Call<Register> register(@Part("photo\"; filename=\"photoName.png\" ") RequestBody photo,
                                     @Part("name") RequestBody name,
                                     @Part("phoneNumber") RequestBody phoneNumber,
                                     @Part("password") RequestBody password,carColor,
                                     @Query("language") String language);


回答2:

you need to add same type for image also see here how it work, This is for multiple images as well.

@Multipart
@POST(ApiConstants.EDIT_REQUEST)
Observable<CommonModel> editRequest(@Part("requestid") RequestBody requestid, @PartMap() Map<String, RequestBody> mapFileAndName);


RequestBody requestid1 = RequestBody.create(MediaType.parse("text/plain"), requestid);

Map<String, RequestBody> files = new HashMap<>();
    for (int i = 0; i < mList.size(); i++) {
        String key = "package_image[" + String.valueOf(i) + "]";
        files.put("" + key + "\"; filename=\"" + key + ".png", getRequestFile(new File(mList.get(i).getImagePath())));
}



private RequestBody getRequestFile(File file) {

    RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
    return fbody;

}

for more details you can visit here



回答3:

Retrofit 2.0 onwards try this answer

@Multipart
@POST("/service/users/add_user")
Call<AddUsersModel> addUser(@Part("user_name") RequestBody userName, @Part("user_last_name") RequestBody lastName, @Part("user_password") RequestBody password,
                               @Part("user_email") RequestBody email, @Part("user_mobile") RequestBody mobile, @Part MultipartBody.Part user_profile);

File path to MulitpartBody.Part convertion

   MultipartBody.Part profileImageBody = null;
        RequestBody reqFile = null;
        try {
            String filePath = CameraIntentUtil.getFIlePath();
            Log.d(TAG, "createAccount: filePath:" + filePath);
            if (filePath != null) {
                File file = new File(filePath);

                reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                // "user_profile" is my post request key
                profileImageBody = MultipartBody.Part.createFormData("user_profile", file.getName(), reqFile);
            }
        } catch (Exception e) {
            Log.e(TAG, "createAccount: ", e);
        }

String to RequestBody convertion

public static RequestBody stringToRequestBody(String data) {
    return RequestBody.create(MediaType.parse("multipart/form-data"), data);
}

Very late answer.. But I hope it help atleast anyone



回答4:

Tested on retrofit 2.3.0

  1. Create interface

    @Multipart
    @POST("edit_profile")
    Call<TokenResponse> getTokenAccess(@PartMap Map<String, RequestBody> 
     map);
    
  2. Call in your Activity

                 Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(getString(R.string.api_coolpool))
                .addConverterFactory(GsonConverterFactory.create())
                .build();
                File file = new File("/storage/sdcard0/Pictures/OGQ/Puskinn 
                Sharma_Jump roof skyscraper_YkRiRWpYcw.jpg");
                 String convert_File_2String= String.valueOf(file);
                 String fileNAme=convert_File_2String.substring(convert_File_2String.lastIndexOf("/")+1);
    RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
    RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "Sunil");
    RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "56");
    RequestBody lastname= RequestBody.create(MediaType.parse("text/plain"), "Kumar");
    Map<String, RequestBody> map = new HashMap<>();
    map.put("profile_pic\"; filename=\""+fileNAme+"\" ", fbody);
    map.put("firstname", name);
    map.put("user_id", id);
    map.put("lastname",lastname);
    
    Call<TokenResponse> tokenResponseCall=service.getTokenAccess(map);
    tokenResponseCall.enqueue(new Callback<TokenResponse>() {
        @Override
        public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
             if (response.isSuccessful())
            Log.e("Success", new Gson().toJson(response.body()));
        else
            Log.e("unSuccess", new Gson().toJson(response.errorBody()));
    }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public void onFailure(Call<TokenResponse> call, Throwable throwable) {
            Log.e("172","><<>>"+throwable);
    
        }
    });