从URL上传图像而不保存它们

时间:2019-07-14 08:42:54

标签: python http python-requests base64

我尝试使用此网址从网址下载图片。

x = requests.get(url).content

这将保存图像,但将其保存为字节。我想知道如何将图像下载为jpeg并在另一个请求中上传,而无需将其下载到我的网址中。

我尝试使用urllib.retrieve函数,但它下载了文件。

1 个答案:

答案 0 :(得分:0)

如果我做对了,您希望将图像从一个站点传输到另一个站点,而无需下载它。

有两种出色的requests功能-iteration over response contentuploading data in chunks

因此您可以分两个步骤进行操作:

  1. 对图像执行GET请求。将其内容处理推迟到步骤2。
  2. 使用Transfer-Encoding: chunked HTTP header将图像内容上传到目标服务器。使用iter_content()生成器按块分割图像内容。

示例:

import requests

# get image without downloading its content
example_jpg_url = "https://2krota.ru/wp-content/uploads/2018/11/fd2880eb2e0275bae3298bd231bd78de.jpg"
download_request = requests.get(example_jpg_url, stream=True)  # no data downloaded yet

# upload image to destination in chunks
destination_url = "http://localhost:8888"
upload_request = requests.post(destination_url, data=download_request.iter_content(8192))
print(upload_request.status_code, upload_request.request.headers)
相关问题