kadik kadik - 6 months ago 100
Android Question

retrofit:2.0.0-beta2 post array of files

I am sending multiple data to server, using retrofit retrofit:2.0.0-beta2.
Data contains array of Files

ArrayList<File>
.
I am using this code to send apart File:

public Call<User> requestUpdateProfile3(String token, File image) {
RequestBody requestBodyImage = RequestBody.create(MediaType.parse("multipart/form-data"), image);
return apiService.updateProfile3(token, requestBodyProfile, requestBodyImage);


and this on ApiService

@Multipart
@POST("/shanyraq/profile/update")
Call<User> updateProfile3(
@Header(value = "X-AUTH-TOKEN") String toke,
@Part("1\"; filename=\"1.jpg") RequestBody image);


Question is: How Can I Post array of Files using retrofit:2.0.0-beta2??

Answer

I have uploaded multiple images as like below. Which uploads images with their names.

Service interface:

    @Multipart
    @POST(ConstantsWebService.UPLOAD_SERVICES_IMAGE)
    Call<List<String>> uploadImage(
             @Header("Authorization") String token,
             //@Part("file\"; filename=\"902367000083-1.jpg") RequestBody mapFileAndName); //for sending only one image
             @PartMap() Map<String,RequestBody> mapFileAndName); //for sending multiple images

And request:

    HashMap<String,RequestBody> map=new HashMap<>(listOfNames.size());
    RequestBody file=null;
    File f=null;

    for(int i=0,size=listOfNames.size(); i<size;i++){
        try {
            f = new File(context.getCacheDir(), listOfNames.get(i)+".jpg");
            FileOutputStream fos = new FileOutputStream(f);
            Bitmap bitmap = getImageFromDatabase(listOfNames.get(i));
            if(bitmap!=null){
                bitmap.compress(Bitmap.CompressFormat.JPEG, 0 /*ignored for PNG*/, fos);
                fos.flush();
                fos.close();
            }else{
                view.showErrorView("imageNotFound"); //todo
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            view.showErrorView("imageNotFound || file not created"); //todo
            return;
        }

        file=RequestBody.create(MediaType.parse("multipart/form-data"), f);
        map.put("file\"; filename=\""+listOfNames.get(i)+".jpg",file);
        file=null;
        f = null;
    }

    serviceOperation.uploadImage(token,map).enqueue(){..}

So you change return type, Header name, image name.