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

如何在Karate中通过Multipart POST请求发送4个文件?两种尝试均失败

Karate多文件Multipart POST请求正确实现方案

你的两种方法核心错误

  1. 方法1:同一个multipart file对象里重复使用read键,JSON对象的键具有唯一性,后面的read会覆盖前面的,实际只会发送最后一个文件,且格式不符合多文件上传要求。
  2. 方法2:定义的变量名(filepathtblBooking等)和multipart里引用的#(file1)不匹配,导致无法读取到文件路径;另外重复使用同一个参数名files时,部分后端可能无法正确识别多文件(取决于后端接收逻辑)。

正确实现方式

场景1:后端支持同一参数名接收多文件(如files)

先确保变量名和引用一致,再逐个添加文件:

# 定义正确的文件路径变量
* def file1 = 'src/test/file1.json'
* def file2 = 'src/test/file2.json'
* def file3 = 'src/test/file3.json'
* def file4 = 'src/test/file4.json'

# 发送Multipart请求
Given url urlUP + querykey
And header Authorization = auth.getBearerToken('Profile', keyClock)
# 每个文件单独添加,参数名统一为files(后端需支持该参数接收多文件)
And multipart file files = { read: '#(file1)', contentType: 'application/json' }
And multipart file files = { read: '#(file2)', contentType: 'application/json' }
And multipart file files = { read: '#(file3)', contentType: 'application/json' }
And multipart file files = { read: '#(file4)', contentType: 'application/json' }
When method post
Then status 200

场景2:后端要求每个文件对应独立参数名(如file1、file2等)

如果后端需要每个文件用不同的字段名接收,按以下方式编写:

# 保留你原来的变量定义
* def filepathtblBooking = 'src/test/file1.json'
* def filepathtblStatus = 'src/test/file2.json'
* def filepathtblBuilding = 'src/test/file3.json'
* def filepathtblRoom = 'src/test/file4.json'

# 发送Multipart请求,每个文件对应不同参数名
Given url urlUP + querykey
And header Authorization = auth.getBearerToken('Profile', keyClock)
And multipart file file1 = { read: '#(filepathtblBooking)', contentType: 'application/json' }
And multipart file file2 = { read: '#(filepathtblStatus)', contentType: 'application/json' }
And multipart file file3 = { read: '#(filepathtblBuilding)', contentType: 'application/json' }
And multipart file file4 = { read: '#(filepathtblRoom)', contentType: 'application/json' }
When method post
Then status 200

批量添加文件(进阶写法)

如果文件数量较多,可以用数组批量设置multipart参数:

# 定义文件列表,指定参数名、路径和类型
* def fileList = [
  { name: 'files', read: 'src/test/file1.json', contentType: 'application/json' },
  { name: 'files', read: 'src/test/file2.json', contentType: 'application/json' },
  { name: 'files', read: 'src/test/file3.json', contentType: 'application/json' },
  { name: 'files', read: 'src/test/file4.json', contentType: 'application/json' }
]
# 将数组设置为multipart参数
* karate.set('multipart', fileList)

Given url urlUP + querykey
And header Authorization = auth.getBearerToken('Profile', keyClock)
When method post
Then status 200

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:45:30