diff --git a/modules/routes/api_upload.py b/modules/routes/api_upload.py new file mode 100644 index 0000000..fd60209 --- /dev/null +++ b/modules/routes/api_upload.py @@ -0,0 +1,57 @@ +""" +图片上传 API +""" +import uuid +import time +import base64 +from flask import Blueprint, request, jsonify +from config import IMAGES_DIR +from utils import allowed_file + +upload_bp = Blueprint('api_upload', __name__) + + +@upload_bp.route('/api/upload/image', methods=['POST']) +def api_upload_image(): + if 'file' not in request.files: + return jsonify({'error': '没有文件'}), 400 + file = request.files['file'] + if file.filename == '': + return jsonify({'error': '没有选择文件'}), 400 + if not allowed_file(file.filename): + return jsonify({'error': '不允许的文件格式'}), 400 + ext = file.filename.rsplit('.', 1)[1].lower() + filename = f"{uuid.uuid4().hex[:12]}_{int(time.time())}.{ext}" + filepath = IMAGES_DIR / filename + file.save(filepath) + return jsonify({'success': True, 'filename': filename, + 'url': f'/static/uploads/{filename}'}) + + +@upload_bp.route('/api/upload/image/base64', methods=['POST']) +def api_upload_image_base64(): + data = request.get_json() + image_data = data.get('image', '') + if not image_data: + return jsonify({'error': '没有图片数据'}), 400 + try: + if 'base64,' in image_data: + image_data = image_data.split('base64,')[1] + ext = data.get('ext', 'png') + filename = f"{uuid.uuid4().hex[:12]}_{int(time.time())}.{ext}" + filepath = IMAGES_DIR / filename + with open(filepath, 'wb') as f: + f.write(base64.b64decode(image_data)) + return jsonify({'success': True, 'filename': filename, + 'url': f'/static/uploads/{filename}'}) + except Exception as e: + return jsonify({'error': str(e)}), 400 + + +@upload_bp.route('/api/upload/image/delete/', methods=['DELETE']) +def api_delete_image(filename): + filepath = IMAGES_DIR / filename + if filepath.exists(): + filepath.unlink() + return jsonify({'success': True}) + return jsonify({'error': '文件不存在'}), 404