Android okHttp addFormDataPart dynamically for Multiple Image

Pratik Butani picture Pratik Butani · Dec 21, 2015 · Viewed 13.4k times · Source

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?

Answer

Pratik Butani picture Pratik Butani · Dec 22, 2015

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.