You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android(Kotlin)使用Retrofit向Spring Boot上传图片列表失败排查

问题分析与解决方案

核心问题

客户端上传的图片列表未被服务端正确接收,根源在于客户端Multipart请求的图片参数名与服务端接收参数名不匹配,同时服务端存在空指针风险。

具体修复步骤

1. 修正客户端API接口的参数命名

客户端Retrofit接口中,图片列表的@Part未指定参数名,导致服务端@RequestParam("imageFiles")无法识别。修改接口定义,明确指定参数名:

@Multipart
@POST("api/property/userId={id}/create")
suspend fun uploadPropertyDetails(
    @Header("Authorization") token: String,
    @Path("id") userId: String,
    @Part("data") property: Property,
    // 新增参数名指定,与服务端保持一致
    @Part("imageFiles") imageFiles: List<MultipartBody.Part>
): Response<PropertyUploadResponse>

2. 确保图片Part的创建使用正确参数名

创建MultipartBody.Part时,必须将表单字段名设置为imageFiles,与服务端接收参数名完全匹配:

// 示例:将选中图片转换为MultipartBody.Part列表
val imageParts = selectedImages.map { imageFile ->
    val requestBody = RequestBody.create(MediaType.parse("image/*"), imageFile)
    // 第一个参数必须为"imageFiles"
    MultipartBody.Part.createFormData("imageFiles", imageFile.name, requestBody)
}

3. 修复服务端空指针异常

服务端直接遍历imageFiles数组,未做null判断,即使参数接收正常,无图片时仍会崩溃。添加null检查:

@PostMapping(value = "property/userId={userId}/create", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public ResponseEntity<Response> addProperty(@RequestPart(value = "data") @Valid PropertyDTO propertyDTO,@PathVariable int userId,
                                            @RequestParam (value = "imageFiles", required = false) MultipartFile[] imageFiles) throws IOException {
    System.out.println("RESPONSE");
    System.out.println();
    System.out.println(propertyDTO.toString());
    System.out.println();
    System.out.println("IMAGE FILES:");
    // 添加null判断,避免空指针
    if (imageFiles != null) {
        for(MultipartFile file : imageFiles) {
            System.out.println(file);
        }
    } else {
        System.out.println("No images uploaded");
    }

    System.out.println();
    return buildResponse("property",propertyService.createProperty(propertyDTO, imageFiles, userId), "Created successfully", HttpStatus.CREATED);
}

额外验证点

  • 检查客户端日志中IMAGE_PARTS的输出,确认每个Part的name字段为imageFiles
  • 确保Retrofit配置未限制Multipart请求大小(若上传大量图片,需在服务端配置spring.servlet.multipart.max-file-size等参数)

内容的提问来源于stack exchange,提问作者Mbogo Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 12:51:10