个股论坛重做
This commit is contained in:
@@ -1192,6 +1192,84 @@ def create_reply(post_id):
|
||||
return api_error(f'创建回复失败: {str(e)}', 500)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 文件上传接口
|
||||
# ============================================================
|
||||
|
||||
import os
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
# 允许的图片扩展名
|
||||
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp'}
|
||||
# 上传目录(相对于 Flask 应用根目录)
|
||||
UPLOAD_FOLDER = 'public/uploads/community'
|
||||
# 最大文件大小 10MB
|
||||
MAX_FILE_SIZE = 10 * 1024 * 1024
|
||||
|
||||
|
||||
def allowed_file(filename):
|
||||
"""检查文件扩展名是否允许"""
|
||||
return '.' in filename and \
|
||||
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
||||
|
||||
|
||||
@community_bp.route('/upload/image', methods=['POST'])
|
||||
@login_required
|
||||
def upload_image():
|
||||
"""
|
||||
上传图片
|
||||
返回图片 URL,可用于帖子内容中
|
||||
"""
|
||||
try:
|
||||
if 'file' not in request.files:
|
||||
return api_error('没有选择文件', 400)
|
||||
|
||||
file = request.files['file']
|
||||
|
||||
if file.filename == '':
|
||||
return api_error('没有选择文件', 400)
|
||||
|
||||
if not allowed_file(file.filename):
|
||||
return api_error('不支持的文件格式,仅支持 PNG、JPG、GIF、WebP', 400)
|
||||
|
||||
# 检查文件大小
|
||||
file.seek(0, 2) # 移动到文件末尾
|
||||
size = file.tell()
|
||||
file.seek(0) # 回到开头
|
||||
|
||||
if size > MAX_FILE_SIZE:
|
||||
return api_error('文件大小超过限制(最大 10MB)', 400)
|
||||
|
||||
# 生成唯一文件名
|
||||
ext = file.filename.rsplit('.', 1)[1].lower()
|
||||
filename = f"{generate_id()}.{ext}"
|
||||
|
||||
# 创建日期目录
|
||||
today = datetime.now().strftime('%Y%m%d')
|
||||
upload_dir = os.path.join(current_app.root_path, UPLOAD_FOLDER, today)
|
||||
os.makedirs(upload_dir, exist_ok=True)
|
||||
|
||||
# 保存文件
|
||||
filepath = os.path.join(upload_dir, filename)
|
||||
file.save(filepath)
|
||||
|
||||
# 返回访问 URL
|
||||
url = f"/uploads/community/{today}/{filename}"
|
||||
|
||||
return api_response({
|
||||
'url': url,
|
||||
'filename': filename,
|
||||
'size': size,
|
||||
'type': f'image/{ext}'
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
print(f"[Community API] 上传图片失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return api_error(f'上传失败: {str(e)}', 500)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ES 代理接口(前端直接查询 ES)
|
||||
# ============================================================
|
||||
|
||||
Reference in New Issue
Block a user