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
相关产品推荐
相关产品推荐

