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

使用Python Boto3 upload_fileobj上传转换后图片至AWS S3失败

问题解决:WebP转JPG后通过BytesIO上传S3为空文件

问题出在BytesIO的读写指针位置:当你通过im.save(jpg_file, "JPEG")将图片数据写入BytesIO对象后,指针会停留在内容的末尾。此时调用s3.upload_fileobj会从当前指针位置开始读取,自然读不到任何数据,最终S3上的文件为空。

解决方法很简单,在调用upload_fileobj之前,将BytesIO的指针重置到起始位置:

r = requests.get(url)
if r.status_code == 200:
    file_name = "name.jpeg"
    s3 = boto3.client("s3")
    webp_file = io.BytesIO(r.content)
    im = Image.open(webp_file).convert("RGB")
    jpg_file = io.BytesIO()
    im.save(jpg_file, "JPEG")
    # 重置文件指针到开头
    jpg_file.seek(0)
    s3.upload_fileobj(
        jpg_file,
        config.app_settings.image_S3_bucket,
        file_name,
        ExtraArgs={"ContentType": "image/jpeg"},
    )

而保存到本地再上传能正常工作,是因为从本地文件读取时,文件指针默认处于起始位置,s3.upload_file可以直接读取完整内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:57:25