| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- # file_uploader.py
- import os
- from flask import request, jsonify
- from files import insert_url
- # 上传目录
- UPLOAD_FOLDER = 'uploads'
- if not os.path.exists(UPLOAD_FOLDER):
- os.makedirs(UPLOAD_FOLDER)
- # 允许的文件扩展名
- ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf','mp4'}
- def allowed_file(filename):
- """检查文件类型是否允许"""
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
- def upload_file():
- """处理文件上传"""
- # 检查请求中是否有文件
- if 'file' not in request.files:
- return jsonify({'error': 'No file part'}), 400
- file = request.files['file']
- # 检查文件是否为空
- if file.filename == '':
- return jsonify({'error': 'No selected file'}), 400
- # 检查文件是否符合要求
- if file and allowed_file(file.filename):
- # 保存文件到服务器
- filename = os.path.join(UPLOAD_FOLDER, file.filename)
- file.save(filename)
- # 返回文件的下载链接
- download_url = f'http://127.0.0.1:5000/download/{file.filename}'
- if not download_url:
- return jsonify({"error": "Missing name or origin"}), 400
- try:
- insert_url(download_url)
- except Exception as e:
- return jsonify({"error": str(e)}), 500
- return jsonify({'message': 'File uploaded successfully', 'download_url': download_url}), 200
- return jsonify({'error': 'File type not allowed'}), 400
|