import os from flask import request, jsonify from werkzeug.utils import secure_filename from db_utils.files import * # 上传目录 UPLOAD_FOLDER = '../uploads' if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) # 允许的文件扩展名 ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'mp4', 'apk'} # 扩展名与数据库表的映射 TABLE_MAPPING = { 'apk': 'apk_table', 'mp4': 'video_table', 'mp3': 'audio_table', 'pdf': 'document_table', 'jpg': 'image_table', 'png': 'image_table', 'jpeg': 'image_table', 'gif': 'image_table' } def allowed_file(filename): """检查文件类型是否允许""" return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS def upload_file(): """处理文件上传""" try: # 检查请求中是否有文件 if 'file' not in request.files: return jsonify({'error': 'No file part in request'}), 400 file = request.files['file'] # 检查文件是否为空 if file.filename == '': return jsonify({'error': 'No selected file'}), 400 # 检查文件是否符合要求 if file and allowed_file(file.filename): # 获取文件扩展名 file_ext = file.filename.rsplit('.', 1)[1].lower() # 获取目标数据库表 target_table = TABLE_MAPPING.get(file_ext) if not target_table: return jsonify({'error': f'No table mapping for file type: {file_ext}'}), 400 # 保存文件到服务器 #filename = secure_filename(file.filename) #格式化文件名 filename = file.filename file_path = os.path.join(UPLOAD_FOLDER, filename) file.save(file_path) # 生成下载链接 download_url = f'http://127.0.0.1:5000/download/{filename}' # 插入数据库 try: result = insert_url(filename, download_url, target_table) print("result:", result) # 调试输出 if result.get("status") == "error": print("发生数据库错误:", result.get("message")) return jsonify({"error": f"Database error: {result.get('message')}"}), 500 else: # 文件插入结果 if result.get("status") == "success": print("文件插入成功!") elif result.get("status") == "duplicate": print(f"文件 {filename} 已存在,不重复插入。") return jsonify({"message": f"文件 {filename} 已经存在"}), 409 else: print("文件插入失败,返回结果:", result.get("file_result")) # 分类表插入结果 if result.get("category_result") and result["category_result"].get("status") == "exists": print("表名已存在,无需插入。") elif result.get("category_result") and result["category_result"].get("status") == "success": print("表名插入成功!") else: print("分类表插入失败,返回结果:", result.get("category_result")) except Exception as e: print("异常信息:", str(e)) return jsonify({"error": f"Database error: {str(e)}"}), 500 return jsonify({'message': 'File uploaded successfully', 'download_url': download_url}), 200 return jsonify({'error': 'File type not allowed'}), 400 except Exception as e: return jsonify({"error": f"Server error: {str(e)}"}), 500