简体   繁体   中英

Android Retrofit: How to upload multiple images to server using retrofit?

First of all this is not a duplicate question as I tired all the method found on stackoverflow already. I am trying to upload multiple(number changes dynamically) images to server using Retrofit library. Currently I am sending two images simultaneously like this

ApiUtil.GetRestApi().UploadImages(
                                  new TypedString(userName), 
                                  new TypedFile("image/jpg", files[0]), 
                                  new TypedFile("image/jpg", files[1]), this);

And my Rest Api looks like this

@Multipart
@POST("/image/upload-media/")
void UploadImages(@Part("username") TypedString userName, 
                  @Part("media") TypedFile media1, 
                  @Part("media") TypedFile media2,
                  Callback<MediaUploadResponse> response);

This works perfectly fine but I cant go ahead with this as number of images can not be fixed. I found many threads on stackoverflow but I could'nt solve this. Any solution for this?

Use retrofit @PartMap. The API will look like:

@Multipart
@POST("/image/upload-media/")
void UploadImages(Map<String,TypedFile> files,
                  Callback<MediaUploadResponse> response);

then create the part map using:

Map<String, TypedFile> files = new HashMap<String, TypedFile>();
files.put("media1", new TypedFile("image/jpg", files(0)));
files.put("media2", new TypedFile("image/jpg", files(1)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM