“Retrofit” multiple images attached in one multipart request

前端 未结 2 1408
我在风中等你
我在风中等你 2020-12-04 11:35

Is there any way to attached multiple images in one multipart request? The images is dynamic based on the number of images that user has picked.

Below code only work

相关标签:
2条回答
  • 2020-12-04 11:59

    After look around with the documentation that provided by retrofit.. Im able to get it done by my own solution, maybe is not that good but still manage to get it works..

    Here is the referece MultipartTypedOutput

    Actually is quite similar to the previous code from above, just make a little bit changes

    Interface

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

    Implementation

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

    Maybe this solution is not that good but hopes it help someone else.

    If there is any better solution please suggest, thank you :D

    Updates

    MultipartTypedOutput no longer exists in Retrofit 2.0.0-beta1

    For those who want to upload multiple images now can use with @PartMap, reference link javadoc

    0 讨论(0)
  • 2020-12-04 12:08
    //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);
    

    //This is the way we can post the file multipartTypedOutput.addPart("profile_doc",new TypedFile("multipart/form-data", postCurriculamFile));

    //This is the way we can post the multiple images

        for (int i = 0; i < images.size(); i++) {
            multipartTypedOutput.addPart("image[]", images.get(i));
        }       
    
    0 讨论(0)
提交回复
热议问题