Search code examples
javaandroidimage-uploadingmultipartokhttp

Uploading multiple image files using okhttp v3.2.0


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;

Solution

  • 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?