feat: 用户头像上传功能
This commit is contained in:
@@ -1,7 +1,7 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""
|
"""
|
||||||
AI Chat App - 后台管理服务
|
AI Chat App - 后台管理服务
|
||||||
端口: 19020 (与前端同一端口)
|
端口: 19021 (与前端同一端口)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from flask import Flask, jsonify, request, send_from_directory
|
from flask import Flask, jsonify, request, send_from_directory
|
||||||
@@ -11,6 +11,7 @@ import json
|
|||||||
import sqlite3
|
import sqlite3
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import base64
|
||||||
|
|
||||||
app = Flask(__name__, static_folder='../www')
|
app = Flask(__name__, static_folder='../www')
|
||||||
CORS(app)
|
CORS(app)
|
||||||
@@ -18,6 +19,11 @@ CORS(app)
|
|||||||
# 数据库路径
|
# 数据库路径
|
||||||
DB_PATH = os.path.join(os.path.dirname(__file__), 'data.db')
|
DB_PATH = os.path.join(os.path.dirname(__file__), 'data.db')
|
||||||
|
|
||||||
|
# 头像存储目录
|
||||||
|
AVATAR_DIR = os.path.join(os.path.dirname(__file__), 'avatars')
|
||||||
|
if not os.path.exists(AVATAR_DIR):
|
||||||
|
os.makedirs(AVATAR_DIR)
|
||||||
|
|
||||||
# 管理员账户(默认)
|
# 管理员账户(默认)
|
||||||
ADMIN_USERNAME = 'admin'
|
ADMIN_USERNAME = 'admin'
|
||||||
ADMIN_PASSWORD_HASH = hashlib.sha256('admin123'.encode()).hexdigest()
|
ADMIN_PASSWORD_HASH = hashlib.sha256('admin123'.encode()).hexdigest()
|
||||||
@@ -610,6 +616,74 @@ def change_user_password(id):
|
|||||||
return jsonify({'success': True})
|
return jsonify({'success': True})
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 用户头像上传 ====================
|
||||||
|
|
||||||
|
@app.route('/api/user/<int:user_id>/avatar', methods=['POST'])
|
||||||
|
def upload_user_avatar(user_id):
|
||||||
|
"""上传用户头像"""
|
||||||
|
data = request.json
|
||||||
|
avatar_data = data.get('avatar') # base64 格式图片
|
||||||
|
|
||||||
|
if not avatar_data:
|
||||||
|
return jsonify({'error': '头像数据不能为空'}), 400
|
||||||
|
|
||||||
|
# 解析 base64 数据
|
||||||
|
try:
|
||||||
|
# 支持两种格式:
|
||||||
|
# 1. data:image/png;base64,xxxxx
|
||||||
|
# 2. 纯 base64 字符串
|
||||||
|
|
||||||
|
if avatar_data.startswith('data:'):
|
||||||
|
# 提取格式和内容
|
||||||
|
header, content = avatar_data.split(',', 1)
|
||||||
|
# 提取图片格式
|
||||||
|
mime_type = header.split(':')[1].split(';')[0]
|
||||||
|
ext = mime_type.split('/')[1] if '/' in mime_type else 'png'
|
||||||
|
else:
|
||||||
|
content = avatar_data
|
||||||
|
ext = 'png'
|
||||||
|
|
||||||
|
# 解码 base64
|
||||||
|
image_bytes = base64.b64decode(content)
|
||||||
|
|
||||||
|
# 验证图片大小(最大 2MB)
|
||||||
|
if len(image_bytes) > 2 * 1024 * 1024:
|
||||||
|
return jsonify({'error': '头像大小不能超过2MB'}), 400
|
||||||
|
|
||||||
|
# 生成文件名
|
||||||
|
filename = f'user_{user_id}_{int(datetime.now().timestamp())}.{ext}'
|
||||||
|
filepath = os.path.join(AVATAR_DIR, filename)
|
||||||
|
|
||||||
|
# 保存文件
|
||||||
|
with open(filepath, 'wb') as f:
|
||||||
|
f.write(image_bytes)
|
||||||
|
|
||||||
|
# 更新数据库(存储文件名)
|
||||||
|
conn = get_db()
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute('UPDATE users SET avatar=?, updated_at=CURRENT_TIMESTAMP WHERE id=?',
|
||||||
|
(filename, user_id))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
return jsonify({'success': True, 'avatar': filename, 'avatar_url': f'/api/avatars/{filename}'})
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'error': f'头像上传失败: {str(e)}'}), 500
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/api/avatars/<filename>', methods=['GET'])
|
||||||
|
def get_avatar(filename):
|
||||||
|
"""获取头像图片"""
|
||||||
|
return send_from_directory(AVATAR_DIR, filename)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/api/admin/users/<int:user_id>/avatar', methods=['POST'])
|
||||||
|
def admin_upload_user_avatar(user_id):
|
||||||
|
"""管理员上传用户头像"""
|
||||||
|
return upload_user_avatar(user_id)
|
||||||
|
|
||||||
|
|
||||||
# ==================== 用户对话数据同步 ====================
|
# ==================== 用户对话数据同步 ====================
|
||||||
|
|
||||||
@app.route('/api/user/<int:user_id>/conversations', methods=['GET'])
|
@app.route('/api/user/<int:user_id>/conversations', methods=['GET'])
|
||||||
|
|||||||
133
www/app.js
133
www/app.js
@@ -1493,6 +1493,9 @@ function renderProfilePage() {
|
|||||||
const userAvatar = currentUser?.avatar || '👤';
|
const userAvatar = currentUser?.avatar || '👤';
|
||||||
const userSignature = currentUser?.signature || '这个人很懒,什么都没写~';
|
const userSignature = currentUser?.signature || '这个人很懒,什么都没写~';
|
||||||
|
|
||||||
|
// 渲染头像(支持 emoji 和上传图片)
|
||||||
|
const avatarHtml = renderAvatar(userAvatar);
|
||||||
|
|
||||||
return `
|
return `
|
||||||
<div class="profile-page">
|
<div class="profile-page">
|
||||||
<header class="page-header">
|
<header class="page-header">
|
||||||
@@ -1502,7 +1505,7 @@ function renderProfilePage() {
|
|||||||
<div class="profile-content">
|
<div class="profile-content">
|
||||||
<!-- 用户卡片 -->
|
<!-- 用户卡片 -->
|
||||||
<div class="profile-user-card" id="userCard">
|
<div class="profile-user-card" id="userCard">
|
||||||
<div class="profile-avatar-large" id="profileAvatar">${userAvatar}</div>
|
<div class="profile-avatar-large" id="profileAvatar">${avatarHtml}</div>
|
||||||
<div class="profile-user-info">
|
<div class="profile-user-info">
|
||||||
<div class="profile-name">${currentUser ? currentUser.username : '游客'}</div>
|
<div class="profile-name">${currentUser ? currentUser.username : '游客'}</div>
|
||||||
<div class="profile-signature">${currentUser ? userSignature : '登录后解锁更多功能'}</div>
|
<div class="profile-signature">${currentUser ? userSignature : '登录后解锁更多功能'}</div>
|
||||||
@@ -1750,6 +1753,9 @@ function renderEditProfilePage() {
|
|||||||
const age = currentUser.age || '';
|
const age = currentUser.age || '';
|
||||||
const region = currentUser.region || '';
|
const region = currentUser.region || '';
|
||||||
|
|
||||||
|
// 渲染头像预览(支持 emoji 和上传图片)
|
||||||
|
const avatarPreviewHtml = renderAvatar(avatar);
|
||||||
|
|
||||||
const editHtml = `
|
const editHtml = `
|
||||||
<div class="edit-profile-page">
|
<div class="edit-profile-page">
|
||||||
<header class="edit-header">
|
<header class="edit-header">
|
||||||
@@ -1763,9 +1769,16 @@ function renderEditProfilePage() {
|
|||||||
<!-- 头像选择 -->
|
<!-- 头像选择 -->
|
||||||
<div class="edit-section">
|
<div class="edit-section">
|
||||||
<div class="edit-avatar-section">
|
<div class="edit-avatar-section">
|
||||||
<div class="edit-avatar-preview" id="editAvatarPreview">${avatar}</div>
|
<div class="edit-avatar-preview" id="editAvatarPreview">${avatarPreviewHtml}</div>
|
||||||
<div class="edit-avatar-label">点击更换头像</div>
|
<div class="edit-avatar-label">点击更换头像</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="avatar-upload-section">
|
||||||
|
<input type="file" id="avatarUploadInput" accept="image/*" style="display: none;">
|
||||||
|
<button class="avatar-upload-btn" id="avatarUploadBtn">
|
||||||
|
<svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M9 16h6v-6h4l-7-7-7 7h4zm-4 2h14v2H5z"/></svg>
|
||||||
|
上传头像
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<div class="avatar-selector" id="avatarSelector">
|
<div class="avatar-selector" id="avatarSelector">
|
||||||
${['👤', '😊', '😎', '🤓', '🧑', '👨', '👩', '🧒', '👴', '👵', '🦸', '🧙', '🤖', '👽', '🥷'].map(a => `
|
${['👤', '😊', '😎', '🤓', '🧑', '👨', '👩', '🧒', '👴', '👵', '🦸', '🧙', '🤖', '👽', '🥷'].map(a => `
|
||||||
<div class="avatar-option ${a === avatar ? 'selected' : ''}" data-avatar="${a}">${a}</div>
|
<div class="avatar-option ${a === avatar ? 'selected' : ''}" data-avatar="${a}">${a}</div>
|
||||||
@@ -1846,9 +1859,28 @@ function renderEditProfilePage() {
|
|||||||
document.getElementById('editAvatarPreview').textContent = newAvatar;
|
document.getElementById('editAvatarPreview').textContent = newAvatar;
|
||||||
document.querySelectorAll('.avatar-option').forEach(o => o.classList.remove('selected'));
|
document.querySelectorAll('.avatar-option').forEach(o => o.classList.remove('selected'));
|
||||||
option.classList.add('selected');
|
option.classList.add('selected');
|
||||||
|
// 清除上传的头像标记
|
||||||
|
uploadedAvatarData = null;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 绑定头像上传按钮
|
||||||
|
const uploadBtn = document.getElementById('avatarUploadBtn');
|
||||||
|
const uploadInput = document.getElementById('avatarUploadInput');
|
||||||
|
|
||||||
|
if (uploadBtn && uploadInput) {
|
||||||
|
uploadBtn.addEventListener('click', () => {
|
||||||
|
uploadInput.click();
|
||||||
|
});
|
||||||
|
|
||||||
|
uploadInput.addEventListener('change', (e) => {
|
||||||
|
const file = e.target.files[0];
|
||||||
|
if (file) {
|
||||||
|
handleAvatarUpload(file);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// 绑定性别选择
|
// 绑定性别选择
|
||||||
document.querySelectorAll('.gender-option').forEach(option => {
|
document.querySelectorAll('.gender-option').forEach(option => {
|
||||||
option.addEventListener('click', () => {
|
option.addEventListener('click', () => {
|
||||||
@@ -1864,8 +1896,58 @@ function renderEditProfilePage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleSaveProfile() {
|
// 上传头像变量
|
||||||
const newAvatar = document.querySelector('.avatar-option.selected')?.getAttribute('data-avatar') || '👤';
|
let uploadedAvatarData = null;
|
||||||
|
|
||||||
|
// 处理头像上传
|
||||||
|
async function handleAvatarUpload(file) {
|
||||||
|
// 验证文件类型
|
||||||
|
if (!file.type.startsWith('image/')) {
|
||||||
|
showToast('请上传图片文件');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证文件大小(最大 2MB)
|
||||||
|
if (file.size > 2 * 1024 * 1024) {
|
||||||
|
showToast('图片大小不能超过2MB');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 读取文件为 base64
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = async (e) => {
|
||||||
|
const base64Data = e.target.result;
|
||||||
|
|
||||||
|
// 显示预览
|
||||||
|
const previewEl = document.getElementById('editAvatarPreview');
|
||||||
|
if (previewEl) {
|
||||||
|
previewEl.innerHTML = `<img src="${base64Data}" style="width: 80px; height: 80px; border-radius: 50%; object-fit: cover;">`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清除预设头像选中状态
|
||||||
|
document.querySelectorAll('.avatar-option').forEach(o => o.classList.remove('selected'));
|
||||||
|
|
||||||
|
// 保存上传的头像数据
|
||||||
|
uploadedAvatarData = base64Data;
|
||||||
|
|
||||||
|
showToast('头像已加载,保存后生效');
|
||||||
|
};
|
||||||
|
reader.readAsDataURL(file);
|
||||||
|
} catch (e) {
|
||||||
|
showToast('头像加载失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSaveProfile() {
|
||||||
|
// 检查是否有上传的头像
|
||||||
|
let newAvatar = uploadedAvatarData;
|
||||||
|
|
||||||
|
// 如果没有上传头像,使用预设头像
|
||||||
|
if (!newAvatar) {
|
||||||
|
newAvatar = document.querySelector('.avatar-option.selected')?.getAttribute('data-avatar') || currentUser.avatar || '👤';
|
||||||
|
}
|
||||||
|
|
||||||
const newUsername = document.getElementById('editUsername')?.value.trim();
|
const newUsername = document.getElementById('editUsername')?.value.trim();
|
||||||
const newSignature = document.getElementById('editSignature')?.value.trim();
|
const newSignature = document.getElementById('editSignature')?.value.trim();
|
||||||
const newEmail = document.getElementById('editEmail')?.value.trim();
|
const newEmail = document.getElementById('editEmail')?.value.trim();
|
||||||
@@ -1874,8 +1956,8 @@ function handleSaveProfile() {
|
|||||||
const newRegion = document.getElementById('editRegion')?.value.trim();
|
const newRegion = document.getElementById('editRegion')?.value.trim();
|
||||||
|
|
||||||
// 验证用户名
|
// 验证用户名
|
||||||
if (!newUsername || newUsername.length < 3 || newUsername.length > 20) {
|
if (!newUsername || newUsername.length < 2 || newUsername.length > 20) {
|
||||||
showToast('用户名需要3-20个字符');
|
showToast('用户名需要2-20个字符');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1902,6 +1984,30 @@ function handleSaveProfile() {
|
|||||||
|
|
||||||
// 如果用户已登录,调用 backend API 更新
|
// 如果用户已登录,调用 backend API 更新
|
||||||
if (currentUser.id) {
|
if (currentUser.id) {
|
||||||
|
// 先处理头像上传(如果有上传的头像)
|
||||||
|
if (uploadedAvatarData) {
|
||||||
|
try {
|
||||||
|
const avatarRes = await fetch(`/api/user/${currentUser.id}/avatar`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ avatar: uploadedAvatarData })
|
||||||
|
});
|
||||||
|
const avatarData = await avatarRes.json();
|
||||||
|
if (avatarData.success && avatarData.avatar_url) {
|
||||||
|
// 使用上传后的头像 URL
|
||||||
|
newAvatar = avatarData.avatar;
|
||||||
|
currentUser.avatar = newAvatar;
|
||||||
|
} else {
|
||||||
|
showToast(avatarData.error || '头像上传失败');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showToast('头像上传失败,请重试');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新用户资料
|
||||||
fetch(`/api/user/${currentUser.id}`, {
|
fetch(`/api/user/${currentUser.id}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
@@ -3978,6 +4084,21 @@ function logStatsToBackend(type, key, value = 1) {
|
|||||||
}).catch(e => console.error('统计记录失败:', e));
|
}).catch(e => console.error('统计记录失败:', e));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 渲染头像(支持 emoji 和上传的图片)
|
||||||
|
function renderAvatar(avatar) {
|
||||||
|
if (!avatar) return '👤';
|
||||||
|
|
||||||
|
// 检查是否是 emoji(单个字符或者预设列表中的)
|
||||||
|
const emojiAvatars = ['👤', '😊', '😎', '🤓', '🧑', '👨', '👩', '🧒', '👴', '👵', '🦸', '🧙', '🤖', '👽', '🥷'];
|
||||||
|
|
||||||
|
if (emojiAvatars.includes(avatar) || avatar.length <= 4) {
|
||||||
|
return avatar;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 否则认为是上传的文件名
|
||||||
|
return `<img src="/api/avatars/${avatar}" style="width: 100%; height: 100%; border-radius: 50%; object-fit: cover;" onerror="this.parentElement.textContent='👤'">`;
|
||||||
|
}
|
||||||
|
|
||||||
// 执行 Tavily 搜索
|
// 执行 Tavily 搜索
|
||||||
async function performSearch(query) {
|
async function performSearch(query) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1049,6 +1049,31 @@ body {
|
|||||||
box-shadow: 0 0 8px rgba(102, 126, 234, 0.3);
|
box-shadow: 0 0 8px rgba(102, 126, 234, 0.3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.avatar-upload-section {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.avatar-upload-btn {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 12px 24px;
|
||||||
|
background: linear-gradient(135deg, var(--primary) 0%, #764ba2 100%);
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 10px;
|
||||||
|
font-size: 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.avatar-upload-btn:hover {
|
||||||
|
transform: scale(1.02);
|
||||||
|
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
.edit-input-group {
|
.edit-input-group {
|
||||||
margin-bottom: 16px;
|
margin-bottom: 16px;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user