Retrofit2でmultipart × multiple images をuploadする

久しぶりにやったらドチャクソハマったのでメモ

interface Service {
    @Multipart
    @POST("upload")
    Call<Response> upload(
            @Part(/* images[] */) MultipartBody.Part[] images,
            @Part("message")
                    RequestBody message);
}
Service service = getService();

List<MultipartBody.Part> parts = new ArrayList<>();

for (String imageUrl: imageUrls) {
    Uri uri = Uri.parse(uriString);
    String mimetype = context.getContentResolver().getType(uri);
    
    if (mimetype == null) continue;

    File tempFile = createTempFile(uri);
    parts.add(MultipartBody.Part.createFormData("images[]", tempFile.getName(), RequestBody.create(MediaType.parse(mimetype), tempFile)));
} 

RequestBody messagePart = RequestBody.create(MultipartBody.FORM, message);

service.upload(parts.toArray(new MultipartBody.Part[0]), messagePart);