You need to enable JavaScript to run this app. 使用RestAssured上传JPEG文件时报has contents that are not what they are reported to be错误
优惠活动
大模型
产品
解决方案
定价
更多

使用RestAssured上传JPEG文件时报has contents that are not what they are reported to be错误

RestAssured 上传JPEG文件报错 'has contents that are not what they are reported to be' 解决方案

该报错核心原因为请求中声明的文件类型与实际上传的二进制内容特征不匹配,可参考以下方案逐一排查解决:

  • 显式指定文件MIME类型
    RestAssured默认会根据文件后缀自动推断MIME类型,部分环境下推断逻辑异常会导致类型不匹配,建议在multiPart方法中强制声明标准JPEG类型image/jpeg:
    given()
      .multiPart("上传参数名", "自定义文件名.jpg", new File("本地JPEG文件完整路径"), "image/jpeg")
      .when()
      .post("目标接口地址")
    
    注意不要使用image/jpg这类非标准MIME写法。
  • 校验本地文件读取状态
    提前确认传入的文件对象合法,避免传入空文件、损坏文件、目录对象导致内容与声明的JPEG类型不符:
    File imageFile = new File("本地JPEG文件完整路径");
    // 提前校验文件状态
    if (!imageFile.exists() || !imageFile.isFile()) {
        throw new RuntimeException("文件不存在或不可读");
    }
    
  • 字节流/数组上传时必须指定带.jpg后缀的文件名
    若你使用InputStream、字节数组而非File对象上传,必须指定带.jpg后缀的文件名,否则RestAssured会默认使用application/octet-stream作为MIME类型,导致校验失败:
    byte[] imageContent = Files.readAllBytes(Paths.get("本地JPEG文件完整路径"));
    given()
      .multiPart("上传参数名", "test.jpg", imageContent, "image/jpeg")
    
  • 不要手动覆盖multipart请求的boundary参数
    不需要手动设置Content-Type: multipart/form-data请求头,RestAssured会自动生成带合法boundary的请求头,手动设置会导致boundary与实际内容分隔符不匹配,触发内容校验错误。可以通过given().log().all()打印完整请求,和Postman导出的curl请求对比参数差异。

内容的提问来源于stack exchange,提问作者Raghu K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 09:27:00