Подтвердить что ты не робот

"Дооснастить" несколько изображений, прикрепленных по одному многопрофильному запросу

Есть ли способ подключить несколько изображений в одном многостраничном запросе? Изображения динамически основаны на количестве изображений, которые пользователь выбрал.

Ниже код работает только для одного изображения:

Интерфейс:

@Multipart
@POST("/post")
void createPostWithAttachments( @Part("f[]") TypedFile image,@PartMap Map<String, String> params,Callback<String> response);

Реализация:

TypedFile file = new TypedFile("image/jpg", new File(gallery.sdcardPath));

Map<String,String> params = new HashMap<String,String>();
params.put("key","value");

ServicesAdapter.getAuthorizeService().createPostWithAttachments(file,params, new Callback<String>() {
        @Override
        public void success(String s, Response response) {
            DBLogin.updateCookie(response);
            new_post_text.setText("");
            try {
                JSONObject json_response = new JSONObject(s);
                Toast.makeText(getApplicationContext(), json_response.getString("message"), Toast.LENGTH_LONG).show();
                if (json_response.getString("status").equals("success")) {
                    JSONObject dataObj = json_response.getJSONObject("data");
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Log.d(TAG, "Request failed");
                }
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            Toast.makeText(getApplicationContext(), retrofitError.getMessage(), Toast.LENGTH_LONG).show();
        }
    });
4b9b3361

Ответ 1

Осмотритесь с документацией, предоставленной путем модернизации. Im, котор нужно сделать его сделанным моим собственным решением, может быть, это не так хорошо, но все же удается заставить его работать.

Вот ссылка MultipartTypedOutput

На самом деле это очень похоже на предыдущий код сверху, просто немного измените

Интерфейс

@POST("/post")
void createPostWithAttachments( @Body MultipartTypedOutput attachments,Callback<String> response);

Реализация

    MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
    multipartTypedOutput.addPart("c", new TypedString(text));
    multipartTypedOutput.addPart("_t", new TypedString("user"));
    multipartTypedOutput.addPart("_r", new TypedString(userData.user.id));

    //loop through object to get the path of the images that has picked by user
    for(int i=0;i<attachments.size();i++){
        CustomGallery gallery = attachments.get(i);
        multipartTypedOutput.addPart("f[]",new TypedFile("image/jpg",new File(gallery.sdcardPath)));
    }

    ServicesAdapter.getAuthorizeService().createPostWithAttachments(multipartTypedOutput, new Callback<String>() {
        @Override
        public void success(String s, Response response) {
            DBLogin.updateCookie(response);
            new_post_text.setText("");
            try {
                JSONObject json_response = new JSONObject(s);
                Toast.makeText(getApplicationContext(), json_response.getString("message"), Toast.LENGTH_LONG).show();
                if (json_response.getString("status").equals("success")) {
                    JSONObject dataObj = json_response.getJSONObject("data");
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Log.d(TAG, "Request failed");
                }
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            Toast.makeText(getApplicationContext(), retrofitError.getMessage(), Toast.LENGTH_LONG).show();
        }
    });

Возможно, это решение не так хорошо, но надеется, что оно поможет кому-то другому.

Если есть какое-либо лучшее решение, пожалуйста, предложите, спасибо: D

Обновление

MultipartTypedOutput больше не существует в Retrofit 2.0.0-beta1

Для тех, кто хочет загрузить несколько изображений, теперь можно использовать с @PartMap, ссылка javadoc

Ответ 2

//We need to create the Typed file array as follow and add the images path in the arrays list.



    private ArrayList<TypedFile> images;

        private void postService(final Context context) {
            Utils.progressDialog(context);
            MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
            multipartTypedOutput.addPart("user_id",new TypedString(strUserId));
            multipartTypedOutput.addPart("title", new TypedString(strJobtitle));
            multipartTypedOutput.addPart("description", new TypedString(
                    strJobdescription));
            multipartTypedOutput.addPart("experience", new TypedString(
                    strUserExperience));
            multipartTypedOutput.addPart("category_id", new TypedString(
                    strPostCategory));
            multipartTypedOutput.addPart("city_id", new TypedString(strCityCode));
            multipartTypedOutput.addPart("country_id", new TypedString(
                    strCountryCode));       
    multipartTypedOutput.addPart("profile_doc",new TypedFile("multipart/form-data", postCurriculamFile));
    for (int i = 0; i < images.size(); i++) {
                multipartTypedOutput.addPart("image[]", images.get(i));
    }       

    PostServiceClient.getInstance().postServiceData(multipartTypedOutput,
                    new Callback<RegistrationResponsModel>() {
                @Override
                public void failure(RetrofitError retrofitError) {
                    Logger.logMessage("fail" + retrofitError);
                    Utils.progressDialogdismiss(context);
                }

                @Override
                public void success(
                        RegistrationResponsModel regProfileResponse,
                        Response arg1) {
                    Utils.progressDialogdismiss(context);
                    UserResponse(regProfileResponse);
                }
            });
        }


    @POST("/service/update") // annotation used to post the data
    void postEditServiceData(@Body MultipartTypedOutput attachments, 
            Callback<RegistrationResponsModel> callback);

//Это способ опубликовать файл multipartTypedOutput.addPart( "profile_doc", новый TypedFile ( "multipart/form-data", postCurriculamFile));

//Это способ опубликовать несколько изображений

    for (int i = 0; i < images.size(); i++) {
        multipartTypedOutput.addPart("image[]", images.get(i));
    }