import os
import boto3
from mimetypes import guess_type
# MinIO 配置信息
MINIO_ENDPOINT = "http://xx:9000" # MinIO 地址
MINIO_ACCESS_KEY = "AT03z5LqjDlaJ4fjn" # MinIO Access Key
MINIO_SECRET_KEY = "jOjWgkDhOc3zC8RgRYLzm4wKP3q4rnR" # MinIO Secret Key
BUCKET_NAME = "lanyuancc" # MinIO 中的桶名
# 本地文件夹路径
LOCAL_FOLDER = r"D:\Backup\Documents\Downloads\蓝源产城图片" # 替换为本地文件夹路径
# 初始化 MinIO 客户端
s3_client = boto3.client(
's3',
endpoint_url=MINIO_ENDPOINT,
aws_access_key_id=MINIO_ACCESS_KEY,
aws_secret_access_key=MINIO_SECRET_KEY
)
def upload_to_minio(local_folder, bucket_name, target_directory=""):
"""
将本地文件夹中的文件上传到 MinIO,支持指定桶内的文件夹路径
:param local_folder: 本地文件夹路径
:param bucket_name: MinIO 中的桶名称
:param target_directory: MinIO 中目标文件夹路径(子目录,例如 "specific-directory")
"""
for root, dirs, files in os.walk(local_folder):
for file_name in files:
local_path = os.path.join(root, file_name) # 本地文件路径
relative_path = os.path.relpath(local_path, local_folder) # 相对路径
# 在 MinIO 中的目标路径,加入指定目录前缀
minio_path = os.path.join(target_directory, relative_path).replace("\\", "/")
mime_type, _ = guess_type(local_path) # 推测文件的 MIME 类型
try:
# 上传文件到 MinIO
s3_client.upload_file(
local_path,
bucket_name,
minio_path,
ExtraArgs={"ContentType": mime_type or "application/octet-stream"}
)
print(f"上传成功: {minio_path}")
except Exception as e:
print(f"上传失败: {minio_path},错误: {e}")
# 调用函数进行文件上传
if __name__ == "__main__":
# 修改 target_directory 为桶中希望的子目录路径
target_directory = "" # 示例子目录:上传到 BUCKET_NAME/specific-directory/
upload_to_minio(LOCAL_FOLDER, BUCKET_NAME, target_directory)