【问题标题】:Uploading image from URL without saving them从 URL 上传图像而不保存它们
【发布时间】:2019-07-14 08:42:54
【问题描述】:

我尝试使用这个从 url 下载图像。

x = requests.get(url).content

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

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

【问题讨论】:

  • 上传是POST方式,所以试试requests.post()
  • 我正在尝试下载图像然后发布。
  • 不用下载,直接使用requests.pos()发送字节即可

标签: python http python-requests base64


【解决方案1】:

如果我没记错的话,您想在不下载的情况下将图像从一个站点传输到另一个站点。

有两个出色的 requests 功能可以做到这一点 - iteration over response contentuploading data in chunks

所以你可以分两步完成:

  1. 对图像执行GET 请求。将其内容处理推迟到第 2 步。
  2. 使用Transfer-Encoding: chunkedHTTP 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)

【讨论】:

    猜你喜欢
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 2017-08-13
    • 2021-10-20
    • 1970-01-01
    • 2022-12-30
    • 2012-03-30
    相关资源
    最近更新 更多