3

This is my code. It properly works. But I want to upload other image types like png, jpeg ,etc. Therefore I want to change filename=\"file1.jpeg"

Also I want to send different number of files at the same time.

Please help me to resolve this. Thank you.

public interface FileUploadService {  
    @Multipart
    @POST("upload")
    Call<ResponseBody> upload(@Part("description") RequestBody description,@Part("file1\"; filename=\"file1.jpeg") RequestBody file1);
}



  private void uploadFile() {  
        FileUploadService service =
                ServiceGenerator.createService(FileUploadService.class);

        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), new File("/path/to/mypic.jpeg"));

        String descriptionString = "hello, this is description speaking";
        RequestBody description =
                RequestBody.create(
                        MediaType.parse("multipart/form-data"), descriptionString);

        Call<ResponseBody> call = service.upload(description, body);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {
                Log.v("Upload", "success");
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("Upload error:", t.getMessage());
            }
        });
    }
  • duplicate of https://stackoverflow.com/questions/34562950/post-multipart-form-data-using-retrofit-2-0-including-image – Matt Wolfe Dec 01 '17 at 17:38

1 Answers1

1

Try this one:

@POST("upload")
fun upload(@BODY parts: MultipartBody): Call<ResponseBody>

and the client side would look like this:

val parts = MultipartBody.Builder()
                    .addFormDataPart(name = "name",filename = "yourDynamicFileName", RequestBody.create(...))
                    .build()
// don't forget to name an extension of your file

api.upload(parts).execute()