问题描述:
我在使用 Python 代码将文件上传到 MinIO 时遇到问题。当我使用Python脚本上传文件时,上传的文件出现在MinIO存储桶中,但没有大小,无法打开。但是,当我手动上传文件时,它们是可见的并且有大小。
我尝试过的:
已验证 MinIO 存储桶设置:我已确认 MinIO 存储桶设置正确,并且手动上传的文件和通过代码上传的文件都存储在正确的存储桶中。
检查内容类型:我使用 get_content_type() 函数正确设置内容类型,以确保正确识别上传的文件。
预期结果:
我希望通过Python脚本上传的文件应该是可见的并且有一个大小,类似于手动上传的文件。
from minio import Minio
from minio.error import S3Error
from flask import Flask, render_template, send_file
from flask_wtf import FlaskForm
from wtforms import FileField, SubmitField
from werkzeug.utils import secure_filename
import os
from wtforms.validators import InputRequired
import mimetypes
minio_client = Minio(endpoint="play.min.io",
access_key="Q3AM3UQ867SPQQA43P2F",
secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG")
app = Flask(__name__)
app.config['SECRET_KEY'] = 'supersecretkey'
class UploadFileForm(FlaskForm):
file = FileField("File", validators=[InputRequired()])
submit = SubmitField("Upload File")
def get_content_type(filename):
content_type, _ = mimetypes.guess_type(filename)
if not content_type:
extension = os.path.splitext(filename)[1].lower()
if extension in ('.jpg', '.jpeg', '.png', '.gif', '.bmp'):
content_type = f'image/{extension.lstrip(".")}'
return content_type or 'application/octet-stream'
@app.route('/', methods=['GET', 'POST'])
@app.route('/home', methods=['GET', 'POST'])
def home():
form = UploadFileForm()
if form.validate_on_submit():
file = form.file.data
filename = secure_filename(file.filename)
bucket_name = "saving-files"
try:
content_type = get_content_type(filename)
minio_client.put_object(bucket_name, filename, file, file.content_length, content_type=content_type)
return "File has been uploaded to MinIO."
except S3Error as e:
return f"Error uploading file to MinIO: {e}"
return render_template('index.html', form=form)
@app.route('/files/<filename>', methods=['GET'])
def get_file(filename):
bucket_name = "saving-files"
try:
file_data = minio_client.get_object(bucket_name, filename)
return send_file(file_data, attachment_filename=filename)
except Exception as e:
return f"Error retrieving file from MinIO: {e}"
if __name__ == '__main__':
app.run(debug=True)
您没有从
request.FILES
读取文件。
# read the file data
file_data = request.FILES[form.file.name].read()
# pass the file data to the `client.put_object`
minio_client.put_object(bucket_name, filename, file_data, file.content_length, content_type=content_type)
https://wtforms.readthedocs.io/en/2.3.x/fields/#wtforms.fields.FileField