kadik kadik - 1 year ago 320
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

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

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 Source

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

Service interface:

    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));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 0 /*ignored for PNG*/, fos);
                view.showErrorView("imageNotFound"); //todo
        } catch (Exception e) {
            view.showErrorView("imageNotFound || file not created"); //todo

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download