在python上使用请求发布图像

PyN*_*bie 3 python python-requests

我正在尝试使用python上的请求上传图像。这是我使用浏览器发送的

POST /upload-photo/{res1}/{res2}/{res3}/ HTTP/1.1
Host: tgt.tgdot.com
Connection: keep-alive
Content-Length: 280487
Authorization: Basic {value}=
Accept: */*
Origin: http://tgt.tgdot.com
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryA8sGeB48ZZCvG127
Referer: http://tgt.tgdot.com/{res1}/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,es;q=0.6
Cookie: fttoken={cookie_value}
Run Code Online (Sandbox Code Playgroud)

这是我的代码

with open(os.getcwd()+"/images/thee1.JPG", "rb") as image_file:
    encoded_image = base64.b64encode(image_file.read())
    headers = {"Content-Type":"multipart/form-data", "Authorization":"Basic " + authvalue}
    cookie = {cookiename: token.value}
    r = requests.post(url, headers =headers, cookies = cookie, params=encoded_image)
    print r.request.headers
    print r.status_code
    print r.text
Run Code Online (Sandbox Code Playgroud)

我不断收到414请求URI太大

我不确定这里缺少什么。我非常感谢您的帮助

Mar*_*ers 6

您正在将整个图像编码为请求参数,从而有效地将URL扩展了图像的长度。

如果您已经编码了图像数据,请使用data参数:

r = requests.post(url, headers=headers, cookies=cookie, data=encoded_image)
Run Code Online (Sandbox Code Playgroud)

请注意,requests可以multipart/form-data直接对POST正文进行编码,不需要您自己对它进行编码。files在这种情况下,请使用参数,传入字典或元组序列。请参阅文档的“ POST多个部分编码文件”部分

该库还可以处理用户名和密码对以处理Authorization标头。只需(username, password)auth关键字参数传入一个元组即可。

但是,将图像编码为Base64 不够。您的内容类型标头和POST有效负载不匹配。相反,您应该使用字段名称发布文件:

with open(os.getcwd()+"/images/thee1.JPG", "rb") as image_file:
    files = {'field_name': image_file}
    cookie = {cookiename: token.value}
    r = requests.post(url, cookies = cookie, files=files, auth=(username, password)
Run Code Online (Sandbox Code Playgroud)