update code

This commit is contained in:
2024-12-26 13:07:55 +08:00
parent d64e709d3f
commit f77dc396db
4 changed files with 217 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
from minio import Minio
from minio.error import S3Error
import mimetypes
import os
def download_file_from_minio(endpoint, access_key, secret_key, bucket_name, object_name):
try:
# 初始化 MinIO 客户端
minio_client = Minio(
endpoint=endpoint,
access_key=access_key,
secret_key=secret_key,
secure=False # 如果 MinIO 没有使用 HTTPS设置为 False
)
# 检查存储桶是否存在
if not minio_client.bucket_exists(bucket_name):
print(f"Bucket '{bucket_name}' does not exist.")
return
# 获取对象元数据
stat = minio_client.stat_object(bucket_name, object_name)
content_type = stat.content_type # 获取 Content-Type
print(f"Object '{object_name}' Content-Type: {content_type}")
# 根据 Content-Type 确定文件后缀
guessed_extension = mimetypes.guess_extension(content_type)
if guessed_extension is None:
guessed_extension = "" # 无法推断时默认不加后缀
print(f"Guessed file extension: {guessed_extension}")
# 提取文件名并设置保存路径
file_name = os.path.basename(object_name) # 提取路径中的文件名
if "." not in file_name: # 如果文件名中没有后缀,添加推断的后缀
file_name += guessed_extension
local_file_path = f"./{file_name}" # 设置保存路径
print(f"File will be saved as: {local_file_path}")
# 下载文件
print(f"Downloading '{object_name}' from bucket '{bucket_name}' to '{local_file_path}'...")
minio_client.fget_object(bucket_name, object_name, local_file_path)
print(f"File '{object_name}' downloaded successfully to '{local_file_path}'.")
except S3Error as e:
print(f"Error occurred: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
# 示例配置
endpoint = "192.168.1.28:9500" # MinIO 服务器地址
access_key = "UIiBRvUixj3GkJwvItmy" # MinIO Access Key
secret_key = "wgIPqYxaNlDhUds0d3n5v57Yvzg3u9iUXplO7Kdm" # MinIO Secret Key
bucket_name = "test-bucket" # 存储桶名称
object_name = "test/uploadedFiles/20241223/175_big.png" # 不带后缀的文件名
# 测试下载文件
download_file_from_minio(endpoint, access_key, secret_key, bucket_name, object_name)