Android okHttp addFormDataPart dynamically for Multiple Image

14,951

Solution 1

This answer is for OkHttp2

For OkHttp3 You can see this post.

For multiple image you just need to run the loop as per your requirement, remaining part related to request will be same as you do.

  //  final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
final MediaType MEDIA_TYPE=MediaType.parse(AppConstant.arrImages.get(i).getMediaType());

//If you can have multiple file types, set it in ArrayList
                    MultipartBuilder buildernew = new MultipartBuilder().type(MultipartBuilder.FORM)
                            .addFormDataPart("title", title)

                    for (int i = 0; i < AppConstants.arrImages.size(); i++) {
                        File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                                TEMP_FILE_NAME + i + ".png");
                        if (f.exists()) {
                            buildernew.addFormDataPart(TEMP_FILE_NAME + i, TEMP_FILE_NAME + i + FILE_EXTENSION, RequestBody.create(MEDIA_TYPE, f));
                        }
                    }
                    RequestBody requestBody = buildernew.build();
                    Request request = new Request.Builder()
                            .url(Url.URL + Url.INSERT_NEWS)
                            .post(requestBody)
                            .build();

                    OkHttpClient client = new OkHttpClient();
                    Response response = client.newCall(request).execute();
                    return response.body().string();

Dont forget to delete temp. files that you uploaded if it is of no use.

Solution 2

Here I have created Function to Upload Multiple Images.

/**
 * Here I am uploading MultipleImages from List of photoCaption
 * Sending photoCaption with URL and Caption of Photo...
 *
 * @param albumId
 * @param photoCaptions
 * @return
 */
public static JSONObject uploadAlbumImage(String albumId, ArrayList<PhotoCaption> photoCaptions) {

    try {

        MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);

        int length = photoCaptions.size();
        int noOfImageToSend = 0;
        for(int i = 0; i < length; i++) {
            /**
             * Getting Photo Caption and URL
             */
            PhotoCaption photoCaptionObj = photoCaptions.get(i);
            String photoUrl = photoCaptionObj.getPhotoUrl();
            String photoCaption = photoCaptionObj.getPhotoCaption();

            File sourceFile = new File(photoUrl);

            if(sourceFile.exists()) {
                /** Changing Media Type whether JPEG or PNG **/
                final MediaType MEDIA_TYPE = MediaType.parse(FileUtils.getExtension(photoUrl).endsWith("png") ? "image/png" : "image/jpeg");

                /** Adding in MultipartBuilder **/
                multipartBuilder.addFormDataPart(KEY_IMAGE_CAPTION + i, photoCaption);
                multipartBuilder.addFormDataPart(KEY_IMAGE_NAME + i, sourceFile.getName(), RequestBody.create(MEDIA_TYPE, sourceFile));

                /** Counting No Of Images **/
                noOfImageToSend++;
            }
        }

        RequestBody requestBody = multipartBuilder
                .addFormDataPart(KEY_ALBUM_ID, albumId)
                .addFormDataPart(KEY_IMAGE_COUNT, String.valueOf(noOfImageToSend))
                .build();

        Request request = new Request.Builder()
                .url(URL_ALBUM_UPLOAD_IMAGE)
                .post(requestBody)
                .build();

        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();

        /** Your Response **/
        String responseStr = response.body().string();

        Log.i(TAG, "responseStr : "+ responseStr);

        return new JSONObject(responseStr);

    } catch (UnknownHostException | UnsupportedEncodingException e) {
        Log.e(TAG, "Error: " + e.getLocalizedMessage());
    } catch (Exception e) {
        Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
    }
    return null;
}

I hope it will helps you.

Share:
14,951
Pratik Butani
Author by

Pratik Butani

Pratik Butani is Android/Flutter Lead at 7Span - Ahmedabad. He is working with Flutter Development since 2020 and Android Development since 2013. He is on the list of Top 100 User’s (85th) in India and Top 10 User’s (6th) in Gujarat as Highest Reputation Holder on StackOverflow. He was co-organizer at Google Developer Group – Rajkot in 2014-17. All-time Learner of new things, Googler and Eager to Help IT Peoples. He is also likes to share his knowledge of Android and Flutter with New Learner. SOReadyToHelp ツ Fell in Love with Android ツ I really feel proud to up-vote My Favorite #SO friend. =&gt; Android Application Developer by Passion :) =&gt; Being Helpful by Nature ;) =&gt; Now in List of Top 100 User's (85) in India and Top 10 User's (6) in Gujarat as Highest Reputation Holder on StackOverflow =&gt; Visit my blogs for learning new things : Happy to Help :) :) =&gt; My Apps on Playstore: AndroidButs &amp; PratikButani =&gt; My Articles on Medium =&gt; Join Me on LinkedIn =&gt; Tweet Me on Twitter =&gt; Follow Me on Quora - Top Writer on Quora in 2017 =&gt; Hangout with Me on [email protected] =&gt; Social Networking Facebook =&gt; Get Users list whose bio's contains given keywords More about me :) -&gt; Pratik Butani

Updated on June 20, 2022

Comments

  • Pratik Butani
    Pratik Butani almost 2 years

    Hello AndroidUploaders,

    I had given answer Uploading a large file in multipart using OkHttp but i am stuck with multiple image uploading.

    I want to upload dynamically 1 to 10 image at a time.

    RequestBody requestBody = new MultipartBuilder()
                        .type(MultipartBuilder.FORM)
                        .addFormDataPart(KEY_PHOTO_CAPTION, photoCaption)
                        .addFormDataPart(KEY_FILE, "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
                        .build();
    

    I have ArrayList of PhotoCaption class which has captionPhoto and urlPhoto so how can i addFormDataPart()

    I am thinking to make loop and call this function that many times of ArrayList size.

    Is there any solution to addFormDataPart() use dynamically?

  • Pratik Butani
    Pratik Butani over 8 years
    I am selecting dynamically like 2 png, 3 gif and 5 jpeg then?
  • PAD
    PAD almost 8 years
    Update May 2016 : MultipartBuilder is now replaced by MultipartBody.Builder ;-)
  • Pratik Butani
    Pratik Butani almost 8 years
    Check Edited Answer for okhttp3
  • Rahul
    Rahul over 5 years
    @PratikButani can you please answer this question i am struck here stackoverflow.com/questions/52520520/…