Retrofit przesyłanie wielu obrazów do jednego klucza

Używam Retrofit do przesyłania obrazów na mój serwer. Tutaj muszę przesłać wiele obrazów dla jednego klucza. Próbowałem z listonoszem web client działa dobrze. Oto zrzut ekranu.

Tutaj wpisz opis obrazka

Oto pary kluczowych wartości dla żądania.
SurveyImage: [file1, file2, file3];
PropertyImage: plik
Dra: jsonBody

Próbowałem zrobić to samo z modernizacją. ale obrazy nie są wgrywanie na serwer.Oto Mój kod.
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);
}

Oto metoda przesyłania plików.

 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");
    }
Proszę, pomóż mi z tym.
Author: John Joe, 2016-10-05

4 answers

Możemy użyć tablicy MultipartBody.Part do przesłania tablicy obrazów do jednego klucza. Oto rozwiązanie
WebServicesAPI

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

Oto metoda przesyłania plików.

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);
}
 45
Author: Kartheek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-20 08:35:58

Zmarnowałem dużo czasu na zaakceptowane ans. ale to nie zadziałało w moim przypadku. Więc po wielu poszukiwaniach znalazłem ten. I działa w 100% w moim przypadku.

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", "[email protected]");

    // 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());
        }
    });


}

A to jest interfejs

@POST("/upload_multi_files/MultiPartUpload.php")
Call<ResponseBody> uploadMultiFile(@Body RequestBody file);
 32
Author: Imran Samed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-07 01:58:20

Najlepsze rozwiązanie kiedykolwiek próbowałem

ApiInterface:

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

Aktywność:

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);
    }
 11
Author: Shofiullah Babor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-24 17:38:39

Pierwszy parametr @ method createFormData klasy MultipartBody.Part jest ciągiem znaków, który jest 'kluczem' lub nazwą wejściową, możesz przekazać ciąg znaków images[] jako tablicę, a później możesz obsłużyć go za pomocą języka zaplecza i zapętlić go, aby uzyskać wszystkie obrazy na pozycji (i)

Sprawdź przykład

 -1
Author: Mohamed abdalmoniem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-06 06:22:53