You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python从公开S3 Bucket URL下载并保存为JPG格式(无需boto3)

解决方法

问题核心是你当前的folder_saving_directory仅指定了文件夹路径,没有设置带.jpg后缀的完整文件名,系统无法识别文件格式。只需修改保存路径为带后缀的完整文件名即可:

基础修改版代码

import requests

amazon_url = "你的公开S3图片URL"
# 指定带.jpg后缀的完整保存路径,比如"./my_image.jpg"
save_path = "./downloaded_image.jpg"

# 发送请求并保存文件
response = requests.get(amazon_url, allow_redirects=True)
if response.status_code == 200:
    with open(save_path, 'wb') as input_file:
        input_file.write(response.content)
else:
    print(f"下载失败,状态码:{response.status_code}")

进阶优化(自动从URL提取文件名)

如果S3 URL本身包含带后缀的文件名,可以自动提取并保存,避免手动命名:

import requests
import os

amazon_url = "你的公开S3图片URL"
folder_path = "./saved_images/"  # 保存文件夹

# 确保目标文件夹存在,不存在则创建
os.makedirs(folder_path, exist_ok=True)
# 从URL提取原文件名(比如URL是xxx/photo.jpg,提取后是photo.jpg)
file_name = os.path.basename(amazon_url)
# 拼接成完整保存路径
save_path = os.path.join(folder_path, file_name)

response = requests.get(amazon_url, allow_redirects=True)
if response.status_code == 200:
    with open(save_path, 'wb') as input_file:
        input_file.write(response.content)
    print(f"图片已保存至:{save_path}")
else:
    print(f"下载失败,状态码:{response.status_code}")

额外验证(确保下载的是JPG)

可以通过响应头的Content-Type验证返回内容是否为JPG:

response = requests.get(amazon_url, allow_redirects=True)
if response.status_code == 200 and response.headers.get('Content-Type') == 'image/jpeg':
    with open(save_path, 'wb') as input_file:
        input_file.write(response.content)
else:
    print("下载的内容不是JPG图片或请求失败")

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:35:32