| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- 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)
- file_path = os.path.join(UPLOAD_FOLDER, filename)
- file.save(file_path)
- # 生成下载链接
- download_url = f'http://127.0.0.1:5000/download/{filename}'
- # 插入数据库
- try:
- insert_url(filename,download_url, target_table)
- except Exception as 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
|