Question Detail

How to choose and Upload Multiple Images to server by using Retrofit in android?

3 years ago Views 2501 Visit Post Reply

Hello All,

I want to upload multiple images or files to Server through APIs in the single key by using Retrofit lib.


Thread Reply

The Developer

- 3 years ago

MediaType mediaType = MediaType.parse("text/plan");
HashMap<String, RequestBody> param = new HashMap<>();
param.put("product_name", RequestBody.create(mediaType, productname));
param.put("OtherValues", RequestBody.create(mediaType, checkisEmptyIntValue("" + products.getWeightUnit())));
            param.put("variant", RequestBody.create(mediaType, variantsConvertintoJson(variantsArrayList))); //VARIENT SHOULD HAS ARRAY OF NEW VERIANTS ONLY

            List<MultipartBody.Part> parts = new ArrayList<>();
            ArrayList<String> imagePthArr = new ArrayList<>();
imagePthArr.add("/emulator/.../.../IMAGEPATH.png");
imagePthArr.add("/emulator/.../.../IMAGEPATH.JPEG");
            if (imagePthArr != null && imagePthArr.size() != 0) {
                for (int i = 0; i < imagePthArr.size(); i++) {
                    String imagePath = imagePthArr.get(i).trim();
                    Log.d("GOINGTOUPLOAD", "IMAGE: " + imagePath);
                    if (!imagePath.isEmpty()) {
                        File finalFile = new File(imagePath);
                        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),
                                finalFile);
                        parts.add(MultipartBody.Part.createFormData("image", "VBage_" + finalFile.getName(),
                                requestBody));
                    }
                }
            }
            Call<ResponseBody> apiCall = apiInterface.addProductAPI(token, param, parts);

apiCall.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {});