Robot Framework中含PDF的Multipart POST请求实现问题
解决Robot Framework中Multipart POST请求带PDF文件的问题
问题根源
你的代码在Evaluate步骤中直接通过字符串插值传递二进制PDF数据,导致bytes类型被错误转换为字符串,引发格式问题;另外使用Get File For Streaming Upload时,没有正确处理返回的文件对象。
解决方案一:正确在Evaluate中引用二进制数据
避免直接在Evaluate的字符串中插入${filedata},改用Python的globals()函数引用Robot Framework变量,保留bytes类型的原始状态:
Create a session for indexing api Create Session indexing_session ${base_url} verify=True Execute indexing api for mortagenumber "${mortgagenumber}" [Arguments] ${type} ${description} ${sendtime} ${source} ${filename} ${filedata}= Get Binary File ${CURDIR}/../testdata/${filename} ${token}= Get new bearer token ${headers}= Create Dictionary Authorization=Bearer ${token} # 通过globals()引用RF变量,避免二进制数据被错误转换 ${formdata}= Evaluate {'type': (None, '${type}', 'text/plain'), 'description': (None, '${description}', 'text/plain'),'sendTime': (None, '${sendtime}', 'text/plain'), 'source': (None, '${source}', 'text/plain'), 'files': ('${filename}', globals()['filedata'], 'application/pdf')} ${response}= POST On Session indexing_session /indexing/${mortgagenumber} headers=${headers} files=${formdata} ${json}= Set Variable ${response.json()} Set Global Variable ${json}
解决方案二:使用Get File For Streaming Upload优化文件传递
Get File For Streaming Upload返回可直接用于流式上传的文件对象,无需手动读取二进制数据,结合Create Dictionary和Set To Dictionary更直观地构建请求参数:
Create a session for indexing api Create Session indexing_session ${base_url} verify=True Execute indexing api for mortagenumber "${mortgagenumber}" [Arguments] ${type} ${description} ${sendtime} ${source} ${filename} ${file_object}= Get File For Streaming Upload ${CURDIR}/../testdata/${filename} ${token}= Get new bearer token ${headers}= Create Dictionary Authorization=Bearer ${token} ${formdata}= Create Dictionary # 添加纯文本参数 Set To Dictionary ${formdata} type=(None, '${type}', 'text/plain') Set To Dictionary ${formdata} description=(None, '${description}', 'text/plain') Set To Dictionary ${formdata} sendTime=(None, '${sendtime}', 'text/plain') Set To Dictionary ${formdata} source=(None, '${source}', 'text/plain') # 添加文件对象 Set To Dictionary ${formdata} files=('${filename}', ${file_object}, 'application/pdf') ${response}= POST On Session indexing_session /indexing/${mortgagenumber} headers=${headers} files=${formdata} ${json}= Set Variable ${response.json()} Set Global Variable ${json}
关键注意事项
- 不要手动设置Content-Type头:
POST On Session底层依赖requests库,会自动为multipart请求生成正确的Content-Type: multipart/form-data; boundary=xxx头,手动设置会覆盖该头导致请求格式错误。 - 参数格式规范:files字典中,纯文本项格式为
(None, 参数值, 'text/plain')(None表示不需要关联文件名);文件项格式为(文件名, 文件对象/二进制数据, MIME类型)。
内容的提问来源于stack exchange,提问作者Peter Franssen
相关产品推荐
相关产品推荐

