file_uploader.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # file_uploader.py
  2. import os
  3. from flask import request, jsonify
  4. from files import insert_url
  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'}
  11. def allowed_file(filename):
  12. """检查文件类型是否允许"""
  13. return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  14. def upload_file():
  15. """处理文件上传"""
  16. # 检查请求中是否有文件
  17. if 'file' not in request.files:
  18. return jsonify({'error': 'No file part'}), 400
  19. file = request.files['file']
  20. # 检查文件是否为空
  21. if file.filename == '':
  22. return jsonify({'error': 'No selected file'}), 400
  23. # 检查文件是否符合要求
  24. if file and allowed_file(file.filename):
  25. # 保存文件到服务器
  26. filename = os.path.join(UPLOAD_FOLDER, file.filename)
  27. file.save(filename)
  28. # 返回文件的下载链接
  29. download_url = f'http://127.0.0.1:5000/download/{file.filename}'
  30. if not download_url:
  31. return jsonify({"error": "Missing name or origin"}), 400
  32. try:
  33. insert_url(download_url)
  34. except Exception as e:
  35. return jsonify({"error": str(e)}), 500
  36. return jsonify({'message': 'File uploaded successfully', 'download_url': download_url}), 200
  37. return jsonify({'error': 'File type not allowed'}), 400