首页 > 解决方案 > 在 Python 中使用请求库上传多部分文件

问题描述

我正在尝试使用Request Libraryin python 上传文件。虽然我收到code 200了,但文件仍然没有上传。

同样的事情也适用于Insomnia

这是python代码-

import requests 
test_url = "https://api.company.net/file/upload/"
my_file = open("C://Certificate.pdf", "rb")       
login_data =  {"email":"admin@company.org", "password":"abc123!"}       
header= {"Content-Type":"multipart/form-data",    "X-Requested-With":"XMLHttpRequest", "Accept-Encoding":"gzip, deflate, br"}     
s = requests.Session() 
login = s.post("https://api.company.net/session/login", json=login_data) 
test_response = s.post(test_url, headers=header, files= {"file": my_file})
print (login.status_code) 
print (login.content) 
print(test_response.text)

输出 -

200

b'{"ok":true,"status":200,"data":"登录成功","errors":null}'

在没有明确指定标题的情况下也进行了尝试,但仍然没有上传文件。

我的机器人框架代码是 -

 *** Variable *** 

 &{headers_file}      Content-Type=multipart/form-data   X-Requested-With=XMLHttpRequest    Accept-Encoding=gzip,deflate,be

 *** Test Cases ***

&{file}    Create Dictionary    file   ${CURDIR}/Certificate.pdf   flowChunkNumber    1   flowChunkSize    1048576    flowCurrentChunkSize    25582   flowTotalSize    25582    flowIdentifier   25582-Certificatepdf    flowFilename   Certificate.pdf    flowRelativePath  Certificate.pdf    flowTotalChunks    1
${test_uri}    Set Variable    /file/upload/
${response}    POST On Session    api_session    ${test_uri}    files=&{file}    headers=&{headers_file}
#VALIDATION
${status}=    Convert To String    ${response.status_code}
Should Be Equal    ${status}    200

谁能帮我解决这个问题?

标签: pythonpython-requestsrequestautomated-testsrobotframework

解决方案


推荐阅读