使用python上的请求发布图像

时间:2015-07-23 17:55:14

标签: 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}

这是我的代码

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

我一直收到414 Request-URI Too Large

我不确定这里缺少什么。我真的很感激帮助

1 个答案:

答案 0 :(得分:4)

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

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

r = requests.post(url, headers=headers, cookies=cookie, data=encoded_image)

请注意,requests可以直接编码multipart/form-data POST主体,您无需自行编码。在这种情况下使用files参数,传入字典或元组序列。请参阅文档的POST Multiple Multipart-Encoded Files section

该库还可以处理用户名和密码对来处理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)