file_uploader.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import os
  2. from flask import request, jsonify
  3. from werkzeug.utils import secure_filename
  4. from db_utils.files import *
  5. # 上传目录
  6. UPLOAD_FOLDER = '../uploads'
  7. if not os.path.exists(UPLOAD_FOLDER):
  8. os.makedirs(UPLOAD_FOLDER)
  9. # 允许的文件扩展名
  10. ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'mp4', 'apk'}
  11. # 扩展名与数据库表的映射
  12. TABLE_MAPPING = {
  13. 'apk': 'apk_table',
  14. 'mp4': 'video_table',
  15. 'mp3': 'audio_table',
  16. 'pdf': 'document_table',
  17. 'jpg': 'image_table',
  18. 'png': 'image_table',
  19. 'jpeg': 'image_table',
  20. 'gif': 'image_table'
  21. }
  22. def allowed_file(filename):
  23. """检查文件类型是否允许"""
  24. return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  25. def upload_file():
  26. """处理文件上传"""
  27. try:
  28. # 检查请求中是否有文件
  29. if 'file' not in request.files:
  30. return jsonify({'error': 'No file part in request'}), 400
  31. file = request.files['file']
  32. # 检查文件是否为空
  33. if file.filename == '':
  34. return jsonify({'error': 'No selected file'}), 400
  35. # 检查文件是否符合要求
  36. if file and allowed_file(file.filename):
  37. # 获取文件扩展名
  38. file_ext = file.filename.rsplit('.', 1)[1].lower()
  39. # 获取目标数据库表
  40. target_table = TABLE_MAPPING.get(file_ext)
  41. if not target_table:
  42. return jsonify({'error': f'No table mapping for file type: {file_ext}'}), 400
  43. # 保存文件到服务器
  44. #filename = secure_filename(file.filename) #格式化文件名
  45. filename = file.filename
  46. file_path = os.path.join(UPLOAD_FOLDER, filename)
  47. file.save(file_path)
  48. # 生成下载链接
  49. download_url = f'http://127.0.0.1:5000/download/{filename}'
  50. # 插入数据库
  51. try:
  52. result = insert_url(filename, download_url, target_table)
  53. print("result:", result) # 调试输出
  54. if result.get("status") == "error":
  55. print("发生数据库错误:", result.get("message"))
  56. return jsonify({"error": f"Database error: {result.get('message')}"}), 500
  57. else:
  58. # 文件插入结果
  59. if result.get("status") == "success":
  60. print("文件插入成功!")
  61. elif result.get("status") == "duplicate":
  62. print(f"文件 {filename} 已存在,不重复插入。")
  63. return jsonify({"message": f"文件 {filename} 已经存在"}), 409
  64. else:
  65. print("文件插入失败,返回结果:", result.get("file_result"))
  66. # 分类表插入结果
  67. if result.get("category_result") and result["category_result"].get("status") == "exists":
  68. print("表名已存在,无需插入。")
  69. elif result.get("category_result") and result["category_result"].get("status") == "success":
  70. print("表名插入成功!")
  71. else:
  72. print("分类表插入失败,返回结果:", result.get("category_result"))
  73. except Exception as e:
  74. print("异常信息:", str(e))
  75. return jsonify({"error": f"Database error: {str(e)}"}), 500
  76. return jsonify({'message': 'File uploaded successfully', 'download_url': download_url}), 200
  77. return jsonify({'error': 'File type not allowed'}), 400
  78. except Exception as e:
  79. return jsonify({"error": f"Server error: {str(e)}"}), 500