import os
from minio import Minio
def upload_dir(prefix, path, bucket_name, minio_client):
"""
#上传文件夹到MInio
:param prefix: 上传到MInio的前缀
:param path: 本地文件夹路径
:param bucket_name: MInio的bucket名
:param minio_client: MInio客户端
:return: 无
"""
stack = []
one = {"file": path, "path": prefix}
stack.append(one)
while stack:
tmp = stack.pop()
file = tmp["file"]
parent_path = tmp["path"]
if os.path.exists(file): # 判断该文夹是否存在
name = os.path.basename(file) # 获取文件名
if os.path.isdir(file): # 判断是否为文件夹
for f in os.listdir(file): # 遍历该文件夹
data = {"file": os.path.join(file, f), "path": parent_path + '/' + name}
stack.append(data) # 将该文件夹的路径和文件名加入栈中,等待上传
else: # 不是文件夹,就开始上传文件
try:
with open(file, 'rb') as file_data: # 打开文件
minio_path = parent_path + '/' + name
suffix = minio_path[minio_path.rfind('.') + 1:] # 获取文件后缀
content_type = None # 设置文件类型
if suffix == 'js':
content_type = 'application/javascript'
elif suffix == 'css':
content_type = 'text/css'
elif suffix == 'png':
content_type = 'image/png'
elif suffix == 'jpg':
content_type = 'image/jpeg'
elif suffix == 'jpeg':
content_type = 'image/jpeg'
elif suffix == 'gif':
content_type = 'image/gif'
elif suffix == 'ico':
content_type = 'image/x-icon'
elif suffix == 'json':
content_type = 'application/json'
elif suffix == 'woff':
content_type = 'font/woff'
elif suffix == 'ttf':
content_type = 'font/ttf'
elif suffix == 'eot':
content_type = 'application/vnd.ms-fontobject'
elif suffix == 'otf':
content_type = 'font/otf'
elif suffix == 'woff2':
content_type = 'font/woff2'
elif suffix == 'map':
content_type = 'application/json'
elif suffix == 'svg':
content_type = 'image/svg+xml'
else: # 其他文件类型,自行设置文件类型
continue # 这里直接跳过,不上传到minio
file_size = os.path.getsize(file)
minio_client.put_object(bucket_name, minio_path, file_data, file_size,
content_type) # 上传文件到minio
# minio_client.put_object(bucket_name, minio_path, file_data, -1, content_type)
except Exception as e:
print("上传失败:", e)
# 使用示例
minio_client = Minio('#',
access_key='#',
secret_key='#',
secure=False)
bucket_name = "erp"
prefix = "js"
path = r"C:\Users\86195\Desktop\dist81"
upload_dir(prefix, path, bucket_name, minio_client)
07-12
2106
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-22
969
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)