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

gcloud-aio-storage无法上传2GB以上文件的问题求助

解决大文件上传的OverflowError问题

错误原因

Windows平台下的Python 3.9对字符串长度存在2GB的限制,一次性读取2GB以上的文件内容到内存时,会触发OverflowError: string longer than 2147483647 bytes。核心解决思路是避免将整个文件加载到内存,改用流式分块上传。

具体解决方案

利用gcloud-aio-storage的可恢复分块上传能力,分块读取文件内容并逐步上传,无需一次性加载完整文件:

import aiofiles
import asyncio
from gcloud.aio.storage import Storage

async def upload_large_file(bucket: str, file_path: str, chunk_size: int = 1024 * 1024 * 8):
    async with Storage() as client:
        # 创建可恢复上传会话
        upload_session = await client.create_resumable_upload_session(
            bucket,
            file_path.split('/')[-1],  # 提取文件名作为云存储对象名
            content_type='application/octet-stream'  # 根据实际文件类型调整(如image/jpeg、text/plain等)
        )
        
        # 分块读取文件并上传
        async with aiofiles.open(file_path, mode='rb') as f:
            while chunk := await f.read(chunk_size):
                await client.upload_chunk(upload_session, chunk)
        
        # 完成上传会话
        await client.complete_resumable_upload(upload_session)

async def uploads(bucket: str, obj_names: list):
    # 并发执行多文件上传(可根据需求改为串行)
    tasks = [upload_large_file(bucket, file) for file in obj_names]
    await asyncio.gather(*tasks)

# 示例调用
if __name__ == '__main__':
    asyncio.run(uploads('你的存储桶名称', ['大文件1.bin', '大文件2.iso']))

关键修改说明

  • 用**二进制模式(rb)**打开文件:避免文本模式的编码转换开销,同时适配绝大多数文件类型的上传需求
  • 分块读取:每次读取8MB(可根据网络带宽调整chunk_size),控制单块内存占用
  • 可恢复上传:支持断点续传,即使上传中断也能从断点继续,提升大文件上传的稳定性
  • 并发上传:利用asyncio.gather实现多文件并行上传,提升整体效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 12:31:09