Retrofit Multipart POST请求如何发送Part列表?
Retrofit发送MultipartBody.Part列表的两种方案
在Retrofit中发送MultipartBody.Part列表(多文件/多个Part),有两种直接可行的方式,无需复杂处理:
方案1:动态索引字段名的List
如果后端接收的是带索引的字段(比如images[0]、images[1]这类格式),可以直接将List<MultipartBody.Part>作为参数,用@Part注解声明:
接口定义
@POST("task/updatedropoff") @Multipart fun taskUpdateDropOff( @Header("apikey") token: String, @PartMap user: HashMap<String, RequestBody>, @Part parts: List<MultipartBody.Part>? = null ): Call<BaseClass<String>>?
构建Part列表
循环创建每个MultipartBody.Part并加入列表:
val imageParts = mutableListOf<MultipartBody.Part>() // 示例:多文件路径集合 val imagePaths = listOf("/sdcard/img1.jpg", "/sdcard/img2.png") imagePaths.forEachIndexed { index, path -> val file = File(path) // 根据文件类型设置MediaType,这里以图片为例 val requestFile = RequestBody.create(MediaType.parse("image/*"), file) // 构建Part,指定字段名带索引 val part = MultipartBody.Part.createFormData("images[$index]", file.name, requestFile) imageParts.add(part) }
方案2:同名字段的List
如果后端接收的是同名字段的多个文件(比如统一用image作为字段名),可以在@Part注解中指定字段名:
接口定义
@POST("task/updatedropoff") @Multipart fun taskUpdateDropOff( @Header("apikey") token: String, @PartMap user: HashMap<String, RequestBody>, @Part("image") images: List<MultipartBody.Part>? = null ): Call<BaseClass<String>>?
构建Part列表
每个Part使用相同的字段名:
val imageParts = mutableListOf<MultipartBody.Part>() imagePaths.forEach { path -> val file = File(path) val requestFile = RequestBody.create(MediaType.parse("image/*"), file) // 统一字段名为"image" val part = MultipartBody.Part.createFormData("image", file.name, requestFile) imageParts.add(part) }
注意事项
MediaType需要和实际文件类型匹配,比如图片用image/jpeg、image/png,视频用video/mp4等;- 后端需要对应配置接收逻辑,比如Spring Boot中可以用
@RequestParam("image") List<MultipartFile> images来接收同名字段的文件列表。
内容的提问来源于stack exchange,提问作者user27376769
相关产品推荐
相关产品推荐

