import io
from minio import Minio
from minio. error import S3Error
from flask import Flask, jsonify, render_template, request, send_file
# 实例化 Flask 应用
app = Flask ( __name__)
# 配置 MinIO 客户端
minio_client = Minio (
"192.168.2.110:58894" ,
access_key= "admins" ,
secret_key= "123qweasd" ,
secure= False # 如果您在使用 HTTPS ,请将其设为 True
)
@app. route ( '/' , methods= [ 'GET' ] )
def home ( ) :
# 获取所有存储桶名称
buckets = minio_client. list_buckets ( )
return render_template ( 'index.html' , buckets= buckets)
@app. route ( '/list' , methods= [ 'GET' ] )
def list_files ( ) :
# 获取要查看的存储桶名称
bucket_name = request. args. get ( 'bucket' )
# 如果未传递存储桶名称,则默认为 'jb02'
if not bucket_name:
bucket_name = 'jb02'
try :
# 获取指定存储桶中的所有文件
objects = minio_client. list_objects ( bucket_name)
files = [ obj. object_name for obj in objects]
# 将文件列表通过 Jinja2 模板引擎渲染为 HTML 页面
# 当用户点击链接时,会触发 / download 路由函数,从而下载指定的文件。
return render_template ( 'list.html' , bucket= bucket_name, files= files)
# 捕获异常并向客户端返回路径不存在错误
except S3Error as e :
print ( e) # 调试用,输出错误信息
return jsonify ( { 'message' : 'path not found' } ) , 404
@app. route ( '/download' , methods= [ 'GET' ] )
def download_file ( ) :
# 获取要下载的文件名称
filename = request. args. get ( 'filename' )
# 获取要下载的存储桶名称
bucket_name = request. args. get ( 'bucket' )
# 如果未传递存储桶名称,则默认为 'jb02'
if not bucket_name:
bucket_name = 'jb02'
try :
# 创建一个可迭代式的迭代器
file_iter = minio_client. get_object ( bucket_name, filename)
# 创建一个可重用的 io. BytesIO 缓冲区
file_data = io. BytesIO ( )
# 从可迭代式迭代器中读取数据,写入缓冲区
for data in file_iter :
#file_data. write ( data. decode ( 'utf-8' ) . encode ( ) )
file_data. write ( data)
# 将缓冲区的内容作为文件发送给客户端
file_data. seek ( 0 )
return send_file (
file_data,
mimetype= 'application/octet-stream' ,
as_attachment= True,
download_name= filename
#cache_timeout= 0
)
# 捕获异常并向客户端返回路径不存在错误
except S3Error as e :
print ( e) # 调试用,输出错误信息
return jsonify ( { 'message' : 'path not found' } ) , 404
if __name__ == '__main__' :
app. run ( debug= True)
创建一个templates目录放入list.html文件
<! DOCTYPE html >
< html>
< head>
< meta charset = " UTF-8" >
< title> MinIO File List</ title>
</ head>
< body>
< h1> MinIO File List - {{ bucket }}</ h1>
< ul>
{% for file in files %}
< li> < a href = " /download?bucket={{ bucket }}&filename={{ file }}" > {{ file }}</ a> </ li>
{% endfor %}
</ ul>
</ body>
</ html>