file_uploader.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. file_path = os.path.join(UPLOAD_FOLDER, filename)
  46. file.save(file_path)
  47. # 生成下载链接
  48. download_url = f'http://127.0.0.1:5000/download/{filename}'
  49. # 插入数据库
  50. try:
  51. insert_url(filename,download_url, target_table)
  52. except Exception as e:
  53. return jsonify({"error": f"Database error: {str(e)}"}), 500
  54. return jsonify({'message': 'File uploaded successfully', 'download_url': download_url}), 200
  55. return jsonify({'error': 'File type not allowed'}), 400
  56. except Exception as e:
  57. return jsonify({"error": f"Server error: {str(e)}"}), 500