python中 requests 传递图片字节流

177 阅读1分钟

在Python中,使用requests库传递图片字节流通常涉及以下几个步骤:

  1. 读取图片文件到字节流。
  2. 使用requests库的postput方法发送HTTP请求,并将图片字节流作为请求体。

示例如下

import requests

# 图片文件的路径
image_path = 'path/to/your/image.jpg'

# 读取图片文件到字节流
with open(image_path, 'rb') as image_file:
    image_bytes = image_file.read()

# 目标URL
url = 'http://example.com/upload'

# 发送POST请求,将图片字节流作为请求体
response = requests.post(url, files={'file': ('filename.jpg', image_bytes)})

# 打印响应内容
print(response.text)