Retrofit Uploading multiple images to a single key

前端 未结 4 710
孤独总比滥情好
孤独总比滥情好 2020-11-28 05:10

I am using Retrofit to upload images to my server. Here I need to upload multiple images for a single key. I have tried with Postman web client it is working well. Here is a

4条回答
  •  时光取名叫无心
    2020-11-28 05:26

    I wasted a lot timing on accepted ans. but that didn't work in my case. So after a lot of search i found this one. And its working 100% in my case.

    private void uploadMultiFile() {
    
    
        ArrayList filePaths = new ArrayList<>();
        filePaths.add("storage/emulated/0/DCIM/Camera/IMG_20170802_111432.jpg");
        filePaths.add("storage/emulated/0/Pictures/WeLoveChat/587c4178e4b0060e66732576_294204376.jpg");
        filePaths.add("storage/emulated/0/Pictures/WeLoveChat/594a2ea4e4b0d6df9153028d_265511791.jpg");
    
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
    
        builder.addFormDataPart("user_name", "Robert");
        builder.addFormDataPart("email", "mobile.apps.pro.vn@gmail.com");
    
        // Map is used to multipart the file using okhttp3.RequestBody
        // Multiple Images
        for (int i = 0; i < filePaths.size(); i++) {
            File file = new File(filePaths.get(i));
            builder.addFormDataPart("file[]", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
        }
    
    
        MultipartBody requestBody = builder.build();
        Call call = uploadService.uploadMultiFile(requestBody);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
    
                Toast.makeText(MainActivity.this, "Success " + response.message(), Toast.LENGTH_LONG).show();
    
    
    
    
            }
    
            @Override
            public void onFailure(Call call, Throwable t) {
    
                Log.d(TAG, "Error " + t.getMessage());
            }
        });
    
    
    }
    

    and this is interface

    @POST("/upload_multi_files/MultiPartUpload.php")
    Call uploadMultiFile(@Body RequestBody file);
    

提交回复
热议问题