2

I am trying to upload multipart data having multiple images (can be none or upto 4 in numbers) using okhttp v3.2.0, the main problem is that, all the data except images is uploaded to server. I tried the source code okhttp have on its recipe page, i also tried Uploading a large file in multipart using OkHttp and File upload with okhttp but did not find any success. The app is not crashing, no errors. But images are not uploaded. I also checked the server side API using POSTMAN and its working fine without any problem. Here is my code, any help is appreciated.

String URL = BASE_URL + "PostRequest.php";
MediaType MEDIA_TYPE;

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String PostDate = sdf.format(c.getTime());

mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(40, TimeUnit.SECONDS)
                .build();

MultipartBody.Builder mRequestBody = new MultipartBody.Builder()
    .setType(MultipartBody.FORM);
    mRequestBody.addFormDataPart("SECURITYCODE",SECURITY_CODE);
    mRequestBody.addFormDataPart("EMAIL", Email);
    mRequestBody.addFormDataPart("CATEGORY", Category);
    mRequestBody.addFormDataPart("SUBCATEGORY", SubCategory);
    mRequestBody.addFormDataPart("TITLE", Title);
    mRequestBody.addFormDataPart("DESCRIPTION", Description);
    mRequestBody.addFormDataPart("LOCATION", Location);
    mRequestBody.addFormDataPart("POSTDATE", PostDate);
    mRequestBody.addFormDataPart("LOCALITY", Locality);
    mRequestBody.addFormDataPart("TOTALIMAGES", Imagepaths.size()+"");

if (Imagepaths.size() > 0) {
    File file = new File(Imagepaths.get(0));
    if (file.exists()) {
        Log.d("file exist", "yes");
    }
    MEDIA_TYPE = Imagepaths.get(0).endsWith("png") ?    
        MediaType.parse("image/png") : MediaType.parse("image/jpeg");
    RequestBody imageBody = RequestBody.create(MEDIA_TYPE, file);
    mRequestBody.addFormDataPart("IMAGE1", "IMAGE1", imageBody);
}

if (Imagepaths.size() > 1) {
    File file = new File(Imagepaths.get(1));
    MEDIA_TYPE = Imagepaths.get(0).endsWith("png") ? 
        MediaType.parse("image/png") : MediaType.parse("image/jpeg");
    RequestBody imageBody = RequestBody.create(MEDIA_TYPE, file);
    mRequestBody.addFormDataPart("IMAGE2", "IMAGE2", imageBody);
}

if (Imagepaths.size() > 2) {
    File file = new File(Imagepaths.get(2));
    MEDIA_TYPE = Imagepaths.get(0).endsWith("png") ? 
        MediaType.parse("image/png") : MediaType.parse("image/jpeg");
    RequestBody imageBody = RequestBody.create(MEDIA_TYPE, file);
    mRequestBody.addFormDataPart("IMAGE3", "IMAGE3", imageBody);
}

if (Imagepaths.size() > 3) {
    File file = new File(Imagepaths.get(3));
    MEDIA_TYPE = Imagepaths.get(0).endsWith("png") ? 
        MediaType.parse("image/png") : MediaType.parse("image/jpeg");
    RequestBody imageBody = RequestBody.create(MEDIA_TYPE, file);
    mRequestBody.addFormDataPart("IMAGE4", "IMAGE4", imageBody);
}

RequestBody rb = mRequestBody.build();

Request request = new Request.Builder()
    .url(URL)
    .post(rb)
    .build();   

try {
    Response mResponse = mOkHttpClient.newCall(request).execute();
        if (!mResponse.isSuccessful()) throw new IOException();

        responseMsg = mResponse.body().string();

} catch (IOException e) {
    responseMsg = timeoutMessage;
}

return responseMsg;
Community
  • 1
  • 1
beginner
  • 528
  • 4
  • 16
  • mRequestBody.addFormDataPart("IMAGE2", "IMAGE2", imageBody); Why you are using two "IMAGE2" key? – Make it Simple Mar 14 '16 at 13:14
  • 1
    Unrelated: That's begging for a for loop. – Eugen Pechanec Mar 14 '16 at 13:17
  • @Make it Simple: one is a key to get the data and second one is the file name. Its my first time with multipart data and okhttp, the recipe page of okhttp also used hardcoded string to pass as a file name also the linked questions i mentioned in my qus did the same thing. – beginner Mar 15 '16 at 04:39
  • @EugenPechanec: yeah, i first tried with a loop, then thought may be the loop is causing problem, so used if. Will use loop again once this get sorted. – beginner Mar 15 '16 at 04:43

1 Answers1

2

First of all you have a couple of errors in your code

Check the mediatype check places, always the same list element (should be index 1,2,3 etc)

   if (Imagepaths.size() > 1) {
        File file = new File(Imagepaths.get(1));

        MEDIA_TYPE = Imagepaths.get(0).endsWith("png") ? 
                MediaType.parse("image/png") : MediaType.parse("image/jpeg");


        RequestBody imageBody = RequestBody.create(MEDIA_TYPE, file);
        mRequestBody.addFormDataPart("IMAGE2", "IMAGE2", imageBody);
    }

Second, mRequestBody.addFormDataPart("IMAGE2", "IMAGE2", imageBody); do you images have the names IMAGE1,IMAGE2, etc?

aelimill
  • 1,015
  • 1
  • 10
  • 17
  • i knew somewhere in my mind that i was doing something wrong, thats why loops are used in such scenario. I corrected the MEDIA_TYPE thing, but the problem still persists. No, my images dont have the IMAGE1, IMAGE2... name but the other examples i went through have used hardcoded strings. Also, to be true, i dont know why the second parameter in "mRequestBody.addFormDataPart("IMAGE2", "IMAGE2", imageBody);" is used. The name of images will be changed on server side according to the ID in table. – beginner Mar 15 '16 at 04:52
  • First param is the key for server (like in dictionary/map). Second param - you need to write your file name which you uploading (like "image_2.png") – aelimill Mar 15 '16 at 08:43
  • thank you for your help, it was the filename thing which i was doing incorrectly. replaced the second parameter with file.getName(); and it worked. Thanx again. – beginner Mar 16 '16 at 04:26