> ## Content Index
> Fetch the complete content index at: https://djdog.cc/llms.txt
> Use this file to discover other available public pages before exploring further.

# 批量下载 Cloudflare R2 中的文件
- URL: https://djdog.cc/blog/2025/r2-download/
- Published: 2025-10-10T04:00:00.000Z
- Updated: 2026-09-24T14:46:43.000Z
- Description: 使用 Python 脚本批量下载 Cloudflare R2 中的文件
- Author: DJDOG
- Tags: Cloudflare, Python, #toc

这里给出使用 AWS SDK for Python（Boto3）的示例，以便后续使用。

## 准备工作

下载 Boto3 库，这里以 `uv` 作为 Python 的包管理器：

```sh
uv add boto3

```

## 运行脚本

```python

# 显式设置R2的访问凭证和配置
s3_client = boto3.client(
    's3',
    aws_access_key_id='YOUR_ACCESS_KEY',
    aws_secret_access_key='YOUR_SECRET_KEY',
    endpoint_url='https://YOUR_ACCOUNT_ID.r2.cloudflarestorage.com',
    region_name='auto'
)

# R2存储桶名称
bucket_name = 'YOUR_BUCKET_NAME'

# 本地存储路径
local_dir = './files'

def download_files(bucket_name, local_dir):
    # 列出存储桶中的所有对象
    response = s3_client.list_objects_v2(Bucket=bucket_name)

    if 'Contents' in response:
        for obj in response['Contents']:
            file_key = obj['Key']
            local_file_path = os.path.join(local_dir, file_key)

            # 创建本地目录
            os.makedirs(os.path.dirname(local_file_path), exist_ok=True)

            # 下载文件
            s3_client.download_file(bucket_name, file_key, local_file_path)
            print(f'Downloaded {file_key} to {local_file_path}')
    else:
        print('No files found in the bucket.')

# 调用下载函数
download_files(bucket_name, local_dir)

```

其中的 `YOUR_ACCESS_KEY` 等需要替换成自己所需要的。

![](https://djdog.cc/content/images/2026/09/cloudflare-text.png)