Retrofit @body with @multipart having Issue

后端 未结 8 1655
星月不相逢
星月不相逢 2020-12-25 08:54

Image Multipart in class type object.

case 1. (Which I had done)

Service params:

{\"id\":\"1\",\"name\":\"vishal\",\"image/file\":\"\"} 
         


        
8条回答
  •  天命终不由人
    2020-12-25 09:10

    https://www.linkedin.com/pulse/retrofit-2-how-upload-multiple-files-server-mahesh-gawale

    I guess the best answer to this question can be found here. It worked perfectly for me.

    This is the example of uploading an array of files using retrofit in Android.

    This is how the service will look like

    public interface ApiService {
    
        @POST("/event/store")
        Call event_store(@Body RequestBody file);
    }
    

    This is how the Client class look like

    public class ApiClient   {
        public static final String API_BASE_URL = "api base url";
    
        private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    
        private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(API_BASE_URL).addConverterFactory(GsonConverterFactory.create());
    
        public static ApiService createService(Class serviceClass)
        {
            Retrofit retrofit = builder.client(httpClient.build()).build();
            return retrofit.create(serviceClass);
        }
    }
    

    Upload like this in activity or fragment or where you want

        ApiService service = ApiClient.createService(ApiService.class);
    
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
    
    
        builder.addFormDataPart("event_name", "xyz");
        builder.addFormDataPart("desc", "Lorem ipsum");
    
        // Single Image
        builder.addFormDataPart("files",file1.getName(),RequestBody.create(MediaType.parse("image/*"), file1));
    
        // Multiple Images 
        for (int i = 0; i  call = service.event_store(requestBody);
        call.enqueue(new Callback() {
             @Override
             public void onResponse(Call call, Response response) {
                 Toast.makeText(getBaseContext(),"All fine",Toast.LENGTH_SHORT).show();
             }
    
             @Override
             public void onFailure(Call call, Throwable t) {
                Toast.makeText(getBaseContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
             }
         });
    

    Note: filePaths.size() is a Arraylist of pickup Images Paths. I hope this post is useful to you. kindly share your feedback as a comment here.

提交回复
热议问题