Python 2.4中的多部分二进制文件POST

1 投票
1 回答
845 浏览
提问于 2025-04-17 11:05

我查了很多代码片段,但还是搞不清楚怎么用Python 2.4在一个请求中同时发送文本和二进制文件。评论里提到过BytesIO类,但在2.4版本里没有这个类。(纯Python,不用第三方库)谢谢。

1 个回答

0

在Python 2.6中,你可以使用requests这个库。下面是从官方文档中提取的一段代码:

>>> url = 'http://httpbin.org/post'
>>> files = {'report.xls': open('report.xls', 'rb')}

>>> r = requests.post(url, files=files)
>>> r.text
{
  "origin": "179.13.100.4",
  "files": {
    "report.xls": "<censored...binary...data>"
  },
  "form": {},
  "url": "http://httpbin.org/post",
  "args": {},
  "headers": {
    "Content-Length": "3196",
    "Accept-Encoding": "identity, deflate, compress, gzip",
    "Accept": "*/*",
    "User-Agent": "python-requests/0.8.0",
    "Host": "httpbin.org:80",
    "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"
  },
  "data": ""
}

撰写回答