简体   繁体   中英

Sending multiple files using multipart.Part

I am trying to send multiple files(images) in gmail but i am not able to send it. I have tried putting the multipart in array but instead of going files in a single mail, two mails are being delivered. My code is as below:

Interface:

public interface EmailService {
@Multipart
@POST("/send/email")
Call<OnlineAushadiModel> sendEmailOnlineAushadi(
                                  @Part("FROM") RequestBody requestFrom,
                                  @Part("TO") RequestBody requestTo,
                                  @Part("SUBJECT") RequestBody requestSubject,
                                  @Part("MailContain") RequestBody requestMailContain,
                                  @Part("FileName") RequestBody requestFileName,
 }

The main Activity:

private void sendData(HashMap<Integer, String> buttons) {
Date today = Calendar.getInstance().getTime();

    to = RequestBody.create(MediaType.parse("text/plain"), "to");
    from = RequestBody.create(MediaType.parse("text/plain"), "bajracharyasudeep@gmail.com");
    subject = RequestBody.create(MediaType.parse("text/plain"), "You have received a new Order.");
    content = RequestBody.create(MediaType.parse("text/plain"),
            "Name: " + HomeActivity.username + "\n" +
                    "Contact Number: " + HomeActivity.phoneNumber + "\n" +
                    "Order date and Time: " + today + "\n" +
                    "Address For Delivery: " + etDeliveryAddress.getText().toString());


    fileName = RequestBody.create(MediaType.parse("text/plain"),"hello");
    fileToUpload = new MultipartBody.Part[buttons.size()];


    for(int i = 0; i<buttons.size();i++){
        Log.e("btnValue", buttons.get(i) + "");
        File file = new File(buttons.get(i));
        RequestBody mFile = RequestBody.create(MediaType.parse("image/" + fileExtension), file);

 fileToUpload[i] = MultipartBody.Part.createFormData("file", file.getName(), mFile);

        emailService  = ApiClient.getApiClientOnlineAushadi().create(EmailService.class);
        Call<OnlineAushadiModel> fileUpload = (Call<OnlineAushadiModel>) emailService.sendEmailOnlineAushadi(to,from,subject,content,fileName,fileToUpload[i]);



        fileUpload.enqueue(new Callback<OnlineAushadiModel>() {
            @Override
            public void onResponse(Call<OnlineAushadiModel> call, Response<OnlineAushadiModel> response) {
                Toast.makeText(getActivity(), "Success " + response.message(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Call<OnlineAushadiModel> call, Throwable t) {
                Log.e("error",t.getMessage() + "");
            }
        });

    }

I have tried other methods such as putting the api call out of the loop but it still didnot helped. Can anybody please help me to send multiple files in Multipart?

You should not upload the file in the loop. Like the code example!

 private void CallAPI() {

    boolean HaveFile;
    final ProgressDialog pd = new ProgressDialog(this);
    pd.setMessage("Uploading...");
    pd.setCancelable(false);
    pd.show();

    ArrayList<MultipartBody.Part> body = new ArrayList<>();
     //image path is a string list of seleted files path
    if (imagePath.size() != 0) {
        for (int i = 0; i < imagePath.size(); i++) {
            //creating a file
            File file = new File(imagePath.get(i));
            //creating request body for file
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            body.add(MultipartBody.Part.createFormData("uploaded_file", file.getName(), requestFile));


        }
        HaveFile=true;
    } else {
        RequestBody attachmentEmpty = RequestBody.create(MediaType.parse(/*"multipart/form-data"*/"text/plain"), "");

        body.add( MultipartBody.Part.createFormData(/*"uploaded_file"*/"attachment", "0736E389-EF21-4286-BEBF-14CCD48B04A6", attachmentEmpty));
        HaveFile=false;
    }




    APIService service =
            ServiceGenerator.getclient().create(APIService.class);

    Call<String> call = service.uploadMulFiles(body.size() == 0 ? null : body ,to,from,subject,content,fileName);
    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(@Nullable Call<String> call,
                               @Nullable Response<String> response) {
            if (response != null) {
                if (response.isSuccessful()) {
                    MainActivity.ComObj.ShowToast(activity_new_ticket.this, response.body() + "", Toast.LENGTH_SHORT);
                    ResetWidjet();
                    pd.cancel();
                } else {
                    try {
                        assert response.errorBody() != null;
                        MainActivity.ComObj.ShowToast(activity_new_ticket.this, response.errorBody().string(), Toast.LENGTH_LONG);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    pd.cancel();
                }
            }
        }

        @Override
        public void onFailure(@Nullable Call<String> call,@Nullable Throwable t) {
            if (t != null) {
                MainActivity.ComObj.ShowToast(activity_new_ticket.this, t.getMessage(), Toast.LENGTH_SHORT);
            }
            pd.cancel();
        }
    });

}

Hope this will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM