Retrofit Uploading multiple images to a single key

2019-01-16 21:17发布

问题:

I am using Retrofit to upload images to my server. Here I need to upload multiple images for a single key. I have tried with Postman web client it is working well. Here is a screenshot.

Here are the key value pairs for the request.
SurveyImage : [file1,file2,file3];
PropertyImage : file
DRA : jsonBody

I tried to do the same with Retrofit. but the images are not uploading to the server.Here is my code.
WebServicesAPI.java

public interface WebServicesAPI {
    @Multipart
    @POST(WebServices.UPLOAD_SURVEY)
    Call<UploadSurveyResponseModel> uploadSurvey(@Part MultipartBody.Part surveyImage, @Part MultipartBody.Part propertyImage, @Part("DRA") RequestBody dra);
}

Here is the method for uploading the files.

 private void requestUploadSurvey() {
        File propertyImageFile = new File(surveyModel.getPropertyImagePath());
        RequestBody propertyImage = RequestBody.create(MediaType.parse("image/*"), propertyImageFile);
        MultipartBody.Part propertyImagePart = MultipartBody.Part.createFormData("PropertyImage", propertyImageFile.getName(), propertyImage);
        JSONObject requestBody = getRequestBody();
        RequestBody draBody = null;
        try {
            draBody = RequestBody.create(MediaType.parse("text/plain"), requestBody.toString(1));
            Log.d(TAG, "requestUploadSurvey: RequestBody : " + requestBody.toString(1));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        MultipartBody surveyImage = null;

            for (SurveyModel.PictureModel model : surveyModel.getPicturesList()) {
                File file = new File(model.getImagePath());
                builder.addFormDataPart("SurveyImage", file.getName(),
                        RequestBody.create(MediaType.parse("image/*"), file));
            }
            surveyImage = builder.build();

        final WebServicesAPI webServicesAPI = RetrofitManager.getInstance().getRetrofit().create(WebServicesAPI.class);
        Call<UploadSurveyResponseModel> surveyResponse = null;

            surveyResponse = webServicesAPI.uploadSurvey(MultipartBody.Part.createFormData("SurveyImage", "SurveyImage", surveyImage), propertyImagePart, draBody);

        surveyResponse.enqueue(this);

        Log.d(TAG, "requestUploadSurvey: sent the request");
    }

Please help me with this.

回答1:

We can use MultipartBody.Part array to upload an array of images to a single key. Here is the solution
WebServicesAPI

public interface WebServicesAPI { 
    @Multipart
    @POST(WebServices.UPLOAD_SURVEY)
    Call<UploadSurveyResponseModel> uploadSurvey(@Part MultipartBody.Part[] surveyImage, @Part MultipartBody.Part propertyImage, @Part("DRA") RequestBody dra);
}

Here is the method for uploading the files.

private void requestUploadSurvey() {
  File propertyImageFile = new File(surveyModel.getPropertyImagePath());
    RequestBody propertyImage = RequestBody.create(MediaType.parse("image/*"), propertyImageFile);
    MultipartBody.Part propertyImagePart = MultipartBody.Part.createFormData("PropertyImage", propertyImageFile.getName(), propertyImage);

    MultipartBody.Part[] surveyImagesParts = new MultipartBody.Part[surveyModel.getPicturesList().size()];

    for (int index = 0; index < surveyModel.getPicturesList().size(); index++) {
        Log.d(TAG, "requestUploadSurvey: survey image " + index + "  " + surveyModel.getPicturesList().get(index).getImagePath());
        File file = new File(surveyModel.getPicturesList().get(index).getImagePath());
        RequestBody surveyBody = RequestBody.create(MediaType.parse("image/*"), file);
        surveyImagesParts[index] = MultipartBody.Part.createFormData("SurveyImage", file.getName(), surveyBody);
    }

    final WebServicesAPI webServicesAPI = RetrofitManager.getInstance().getRetrofit().create(WebServicesAPI.class);
    Call<UploadSurveyResponseModel> surveyResponse = null;
    if (surveyImagesParts != null) {
        surveyResponse = webServicesAPI.uploadSurvey(surveyImagesParts, propertyImagePart, draBody);
    }
    surveyResponse.enqueue(this);
}


回答2:

I wasted a lot timing on accepted ans. but that didn't work in my case. So after a lot of search i found this one. And its working 100% in my case.

private void uploadMultiFile() {


    ArrayList<String> filePaths = new ArrayList<>();
    filePaths.add("storage/emulated/0/DCIM/Camera/IMG_20170802_111432.jpg");
    filePaths.add("storage/emulated/0/Pictures/WeLoveChat/587c4178e4b0060e66732576_294204376.jpg");
    filePaths.add("storage/emulated/0/Pictures/WeLoveChat/594a2ea4e4b0d6df9153028d_265511791.jpg");

    MultipartBody.Builder builder = new MultipartBody.Builder();
    builder.setType(MultipartBody.FORM);

    builder.addFormDataPart("user_name", "Robert");
    builder.addFormDataPart("email", "mobile.apps.pro.vn@gmail.com");

    // Map is used to multipart the file using okhttp3.RequestBody
    // Multiple Images
    for (int i = 0; i < filePaths.size(); i++) {
        File file = new File(filePaths.get(i));
        builder.addFormDataPart("file[]", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
    }


    MultipartBody requestBody = builder.build();
    Call<ResponseBody> call = uploadService.uploadMultiFile(requestBody);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            Toast.makeText(MainActivity.this, "Success " + response.message(), Toast.LENGTH_LONG).show();




        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {

            Log.d(TAG, "Error " + t.getMessage());
        }
    });


}

and this is interface

@POST("/upload_multi_files/MultiPartUpload.php")
Call<ResponseBody> uploadMultiFile(@Body RequestBody file);


回答3:

Best solution ever I have tried

ApiInterface:

@Multipart
    @POST("person/img")
    Call<ResponseBody> upImageMany(@Part List<MultipartBody.Part> file);

Activity:

List<MultipartBody.Part> parts = new ArrayList<>();

for (int i=0; i < upFileList.size(); i++){
    parts.add(prepareFilePart("my_file["+i+"]", upFileList.get(i)));
}

private MultipartBody.Part prepareFilePart(String partName, Uri fileUri){

        File file = new File(getPath(fileUri));

        RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);

        return MultipartBody.Part.createFormData(partName, file.getName(),requestBody);
    }


回答4:

The first parameter @method createFormData of class MultipartBody.Part is a string, which is the 'key' or the input name, you can pass the string images[] as an array, and later on you can handle it with your backend language and loop over it to get all the images at position (i)

check example