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

Karate中Multipart POST请求异常,Postman可正常运行求助

解决Karate Multipart文件上传400(MIME类型错误)问题

核心问题分析

你遇到的问题根源有两点:

  • Karate默认会给multipart文件字段自动追加charset=UTF-8后缀,后端不识别带该参数的MIME类型,导致返回400
  • 代码中错误地将单个文件的contentType设为multipart/form-data(这是整个请求的Content-Type,单个文件需对应真实MIME类型,比如txt文件用text/plain)
  • 文件读取方式差异导致content-length和Postman不一致,进一步触发后端校验异常

具体解决方案

1. 修正文件的Content-Type

将multipart配置里的contentType改为文件真实的MIME类型,示例中txt文件应设置为text/plain:

And multipart file file = { read: '#(filePath)', filename: 'file.txt', contentType: 'text/plain' }

2. 彻底移除Charset参数

仅设置configure charset = null无法完全移除multipart字段的charset,需结合二进制读取文件的方式绕过自动编码逻辑:

* def fileContent = read('classpath:file.txt', 'binary')
* multipart field file = { value: fileContent, filename: 'file.txt', contentType: 'text/plain' }

3. 对齐文件读取模式保证content-length一致

Postman以二进制模式读取文件,Karate默认文本读取会导致编码转换,用binary模式读取可确保文件内容和长度与Postman完全一致:

* def fileContent = read('#(filePath)', 'binary')
And multipart file file = { value: fileContent, filename: 'file.txt', contentType: 'text/plain' }

调整后的完整代码示例

Feature: File upload

  Background:
    Given url baseUrl
    # initiate authentication
  
  @form-data
  Scenario: Uploading file 
    * def filePath = 'classpath:file.txt'
    * configure headers = {'Authorization': '#(authorization)', Accept: 'application/json'}
    * configure charset = null
    Given path fileConversionApi
    * def fileContent = read('#(filePath)', 'binary')
    And multipart file file = { value: fileContent, filename: 'file.txt', contentType: 'text/plain' }
    When method post
    Then status 200
    Then print response

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 02:05:11