Skip to content Skip to sidebar Skip to footer

Retrofit 2 Multipart Image Upload With Data

Hello everyone I want to post image and other data through Retrofit2. I am sending data with one image. All the other info is storing but my image is not storing.while i am testi

Solution 1:

We test api in Postman... So my Create Post Answer includes (all Dynamic)

  • Headers
  • Simple Strings
  • Single Image
  • Array Of Images
  • Array Of Categories
  • Array Of Features

Almost all things

Below is the Postman image for api testing... You will get clear concept of request

  • Headers Image

enter image description here

So for this ... Below is my Api...

@POST("post-create")
    Call<PostCreateResponse> getPostCreateBodyResponse(
            @Header("Accept") String accept,
            @Header("Authorization") String authorization,
            @Body RequestBody file
    );

Now Retrofit Client area--->

private Retrofit retrofit;

// This is ClientprivateRetrofitClient() {

        HttpLoggingInterceptorlogging=newHttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.BuilderhttpClient=newOkHttpClient.Builder();

        httpClient.connectTimeout(100, TimeUnit.SECONDS);
        httpClient.readTimeout(100,TimeUnit.SECONDS);
        httpClient.writeTimeout(100,TimeUnit.SECONDS);
        httpClient.addInterceptor(logging);  // <-- this is the important line!

        retrofit = newRetrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build();
    }

This is the way I Made the Request...

/*
     * -------------- Retrofit post Create single featured Image Working with MultipartBody -----------
     * */

    progressDialog.show();

    MultipartBody.Builderbuilder=newMultipartBody.Builder().setType(MultipartBody.FORM);

    builder.addFormDataPart("title", "3 room Current Free")
            .addFormDataPart("location", "Dhaka")
            .addFormDataPart("latitude", "23.7515")
            .addFormDataPart("longitude", "90.3625")
            .addFormDataPart("condition", "1")
            .addFormDataPart("rent_amount", "123456")
            .addFormDataPart("is_negotiable", "0")
            .addFormDataPart("available_from", "2018-10-15");

    // Categoriesfor (int categoryId : categories) {
        builder.addFormDataPart("categories[]", String.valueOf(categoryId));
    }
    // Featuresfor (Integer featureId : features) {
        builder.addFormDataPart("features[]", String.valueOf(featureId));
    }

    // featured Imageif (photoPaths.get(0) != null) {
        Filefeatured_image=newFile(photoPaths.get(0));
        if (featured_image.exists()) {

// If you want to use Bitmap then use thisBitmapbmp= BitmapFactory.decodeFile(featured_image.getAbsolutePath());
            ByteArrayOutputStreambos=newByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 30, bos);

            builder.addFormDataPart("featured_photo", featured_image.getName(), RequestBody.create(MultipartBody.FORM, bos.toByteArray()));


// If you want to use direct file then use this ( comment out the below part and comment the above part )//builder.addFormDataPart("featured_photo", featured_image.getName(), RequestBody.create(MultipartBody.FORM, featured_image));
        }
    }

    // Imagesfor (String photoPath : photoPaths) {
        if (photoPath != null) {
            Fileimages=newFile(photoPath);
            if (images.exists()) {
                builder.addFormDataPart("images[]", images.getName(), RequestBody.create(MultipartBody.FORM, images));
            }
        }
    }

    RequestBodyrequestBody= builder.build();
    Call<PostCreateResponse> call = RetrofitClient.getInstance().getApi().getPostCreateBodyResponse(Accept, Authorization, requestBody);
    call.enqueue(newCallback<PostCreateResponse>() {
        @OverridepublicvoidonResponse(Call<PostCreateResponse> call, Response<PostCreateResponse> response) {
            progressDialog.dismiss();
            Log.d(TAG, "onResponse: response code: retrofit: " + response.code());
        }

        @OverridepublicvoidonFailure(Call<PostCreateResponse> call, Throwable t) {

        }
    });

    /*
     * ---------------- Retrofit post Create single featured Image Working with MultipartBody----------------
     * */

I hope this will help you all... thanks

Solution 2:

get Image like this

UrimImageUri= data.getData();

// Get the cursorCursorcursor= getContentResolver().query(mImageUri, 
    filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();

intcolumnIndex= cursor.getColumnIndex(filePathColumn[0]);
imageURI = cursor.getString(columnIndex);
cursor.close(); 

Filefile=newFile(mImageUri.getPath())
RequestBodyreqFile= RequestBody.create(okhttp3.MediaType.parse("image/*"), file);
MultipartBody.Partbody= MultipartBody.Part.createFormData("image",
    file.getName(), reqFile);

Solution 3:

This is my activity code where i am using multipart to show images, follow this code:

publicvoiduploadimage()
{
    StringfilePath= getRealPathFromURIPath(uri1, DriverDetails.this);
    Log.d("hanish123456","File path->  "+filePath);
    file1 = newFile(filePath);
    Log.d("uploadimage", "Filename " + profileimage1);
    Bitmapbmp= BitmapFactory.decodeFile(file1.getAbsolutePath());
    ByteArrayOutputStreambos=newByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 30, bos);

    MultipartBody.PartfileToUpload= MultipartBody.Part.createFormData("image", profileimage1,
            RequestBody.create(MediaType.parse("image/*"), bos.toByteArray()));
    RequestBodyfilename= RequestBody.create(MediaType.parse("text/plain"), profileimage1);

    OkHttpClientclient=newOkHttpClient.Builder()
            .connectTimeout(3, TimeUnit.MINUTES)
            .readTimeout(3,TimeUnit.MINUTES)
            .writeTimeout(3,TimeUnit.MINUTES).build();

    Retrofitretrofit=newRetrofit.Builder()
            .baseUrl(SERVER_PATH)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    ApiServiceuploadImage= retrofit.create(ApiService.class);

    Log.d("uploadimage", fileToUpload+"   "+filename);
    Call<ProfileResponse> fileUpload = uploadImage.uploadFile(fileToUpload, filename);
    fileUpload.enqueue(newCallback<ProfileResponse>() {
        @OverridepublicvoidonResponse(Call<ProfileResponse> call, Response<ProfileResponse> response) {
            if(response.isSuccessful()){
                Toast.makeText(DriverDetails.this,"Successful  "+ response.raw().message(), Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(DriverDetails.this, response.raw().message(), Toast.LENGTH_LONG).show();
            }
            // Toast.makeText(MainActivity.this, "Success " + response.body().getSuccess(), Toast.LENGTH_LONG).show();
            Log.d("uploadimage", "No Error ");
        }
        @OverridepublicvoidonFailure(Call<ProfileResponse> call, Throwable t) {
            if (t instanceof SocketTimeoutException) {
                Log.d("uploadimage", "Error occur " + t.getMessage());
            }
        }
    });
}

Solution 4:

there one more simple way to send other data, you can send Hashmap<String,String>

@Multipart@POST("sign-up")
    Call<SignUpResponse> getSignUpResponse(@Part MultipartBody.Part file, @PartMap() Map<String, String> partMap); 

Post a Comment for "Retrofit 2 Multipart Image Upload With Data"