Search code examples
androidmultipartretrofit

"Retrofit" multiple images attached in one multipart request


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 works for single image:

Interface:

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

Implementation:

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

Solution

  • 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