Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中使用请求上载文件_Python_Python 3.x_Python Requests - Fatal编程技术网

如何在Python中使用请求上载文件

如何在Python中使用请求上载文件,python,python-3.x,python-requests,Python,Python 3.x,Python Requests,我试图通过Python请求上传文件,但收到错误代码400(错误请求) 如果我尝试通过邮递员这是成功的使用以下代码 url = "https://<url>" payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"; filename=\"C:\\Users\\<filename>\"\r\nContent-Type: text/c

我试图通过Python请求上传文件,但收到错误代码400(错误请求)

如果我尝试通过邮递员这是成功的使用以下代码

url = "https://<url>"
payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"; filename=\"C:\\Users\\<filename>\"\r\nContent-Type: text/csv\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
'Authorization': "TOKEN id="3e9d095d-a47b-48b5-a0b8-ae8b8ad9ae74"",
'cache-control': "no-cache",
'Postman-Token': "bb155176-b1b8-47a6-8fb3-46f5740cf9e0"
}

response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
url=“https://”
payload=“---WebKitFormBoundary7MA4YWxkTrZu0gW\r\n内容处理:表单数据;名称=\“文件\”文件名=\“C:\\Users\\”\r\n内容类型:text/csv\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--”
标题={
“内容类型”:“多部分/表单数据;边界=----WebKitFormBoundary7MA4YWxkTrZu0gW”,
“授权”:令牌id=“3e9d095d-a47b-48b5-a0b8-ae8b8ad9ae74”,
“缓存控制”:“无缓存”,
“邮递员令牌”:“bb155176-b1b8-47a6-8fb3-46f5740cf9e0”
}
响应=请求。请求(“POST”,url,数据=有效负载,标题=标题)
打印(response.text)

有什么不对吗?

您应该改用
文件
参数。另外,不要在标题中明确设置
内容类型
,以便
请求
可以为您设置适当的边界:

header_upload_file = {
    'Authorization': 'TOKEN id="' + token + '"'
}
response = requests.post(
    baseurl + '/incidents/number/' + ticket_number + '/attachments/',
    headers=header_upload_file,
    files={'file': ('file', open(main_path + '/temp/test.txt', 'rb'), 'text/csv')},
    verify=certificate
)

遗憾的是没有成功我已经用文件的显式内容类型更新了我的答案。
header_upload_file = {
    'Authorization': 'TOKEN id="' + token + '"'
}
response = requests.post(
    baseurl + '/incidents/number/' + ticket_number + '/attachments/',
    headers=header_upload_file,
    files={'file': ('file', open(main_path + '/temp/test.txt', 'rb'), 'text/csv')},
    verify=certificate
)