【问题标题】:Sending images by POST using python requests使用 python 请求通过 POST 发送图像
【发布时间】:2020-05-12 16:48:19
【问题描述】:

我正在尝试使用以下代码发送图像:这只是我的代码的一部分,我没有在此处包含标题,但它们设置正确,内容类型为content-type: multipart/form-data; boundary=eBayClAsSiFiEdSpOsTiMaGe

img = "piano.jpg"
f = open(img,'rb')
out = f.read()
files = {'file':out}

p = requests.post("https://ecg-api.gumtree.com.au/api/pictures",headers=headers, data=files)
f.close()

我收到 400 错误 incorrect multipart/form-data format

如何正确发送图片?

额外细节:

网络分析显示已发送以下请求:

POST https://ecg-api.gumtree.com.au/api/pictures HTTP/1.1
host:   ecg-api.gumtree.com.au
content-type:   multipart/form-data; boundary=eBayClAsSiFiEdSpOsTiMaGe
authorization:  Basic YXV5grehg534
accept: */*
x-ecg-ver:  1.49
x-ecg-ab-test-group:    gblios_9069_b;gblios-8982-b
accept-encoding:    gzip
x-ecg-udid: 73453-7578p-8657
x-ecg-authorization-user:   id="1635662", token="ee56hgjfjdghgjhfj"
accept-language:    en-AU
content-length: 219517
user-agent: Gumtree 12.6.0 (iPhone; iOS 13.3; en_AU)
x-ecg-original-machineid:   Gk435454-hhttehr

Form data:
file: ����..JFIF.....H.H..��.LExif..MM.*..................�i.........&......�..

我把文件的formdata部分剪掉了,因为它太长了。我的标头是这样写的(我在这里编了实际的 auth 值):

idd = "1635662"
token = "ee56hgjfjdghgjhfj"

headers = {
"authority":"ecg-api.gumtree.com.au",
"content-type":"multipart/form-data; boundary=eBayClAsSiFiEdSpOsTiMaGe",
"authorization":"Basic YXV5grehg534",
"accept":"*/*",
"x-ecg-ver":"1.49",
"x-ecg-ab-test-group":"gblios_9069_b;gblios-8982-b",
"accept-encoding":"gzip",
"x-ecg-udid":"73453-7578p-8657",
"x-ecg-authorization-user":f"id={idd}, token={token}",
"accept-language":"en-AU",
"content-length":"219517",
"user-agent":"Gumtree 12.6.0 (iPhone; iOS 13.3; en_AU)",
"x-ecg-original-machineid":"Gk435454-hhttehr"
}

也许是我写标题的方式?我怀疑这是我在标题中编写x-ecg-authorization-user 部分的方式?因为我意识到即使为令牌或 id 设置随机值也会给我同样的 400 错误incorrect multipart/form-data format

【问题讨论】:

  • 这能回答你的问题吗? stackoverflow
  • @Ahmet 我在那里尝试了所有答案,但仍然收到incorrect multipart/form-data format 错误
  • @Ahmet 我怀疑这是我在标题中编写x-ecg-authorization-user 部分的方式?因为我意识到即使为令牌或 id 设置随机值也会给我同样的 400 错误incorrect multipart/form-data format
  • 这给了我401:unauthorised 而不是400
  • @Ahmet 请记住我发布的授权值不是实际值

标签: python post python-requests


【解决方案1】:

你可以试试下面的代码。不要在 headers 中设置 content-type。让 Pyrequests 为你做这件事

files = {'file': (os.path.basename(filename), open(filename, 'rb'), 'application/octet-stream')}
upload_files_url = "url"
headers = {'Authorization': access_token, 'JWTAUTH': jwt}
r2 = requests.post(parcels_files_url, files=files, headers=headers)

【讨论】:

  • 谢谢!删除内容类型有效,以及在 POST 中使用 files=files 而不是 data=files
猜你喜欢
  • 2018-04-20
  • 2015-07-24
  • 2021-08-02
  • 2019-11-24
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多