51 lines
2.0 KiB
Python
51 lines
2.0 KiB
Python
import os
|
||
from fastapi import APIRouter, UploadFile, File, Form, HTTPException
|
||
from pathlib import Path
|
||
from database.database import new_session
|
||
import shutil
|
||
from database.enums.type_file import FileType
|
||
from repositories.uploaded_file_repository import UploadedFileRepository
|
||
|
||
router = APIRouter()
|
||
|
||
UPLOAD_FOLDER_CSV = Path("uploads/file")
|
||
UPLOAD_FOLDER_CSV.mkdir(parents=True, exist_ok=True)
|
||
|
||
@router.post("/upload/file/")
|
||
async def upload_file(user_id: int, user_name: str, file: UploadFile = File(...), file_type: FileType = Form(...)):
|
||
|
||
# Проверяем, что тип файла корректен
|
||
if file_type not in FileType:
|
||
raise HTTPException(status_code=400, detail="Неверный тип файла")
|
||
|
||
# Формируем путь для сохранения
|
||
user_folder = UPLOAD_FOLDER_CSV / (str(user_id) + "_" + user_name)
|
||
user_folder.mkdir(parents=True, exist_ok=True)
|
||
file_path = user_folder / file.filename
|
||
|
||
# Сохраняем файл на диск
|
||
try:
|
||
with open(file_path, "wb") as buffer:
|
||
shutil.copyfileobj(file.file, buffer)
|
||
except Exception as e:
|
||
raise HTTPException(status_code=500, detail=f"Ошибка при сохранении файла: {str(e)}")
|
||
|
||
# Получаем размер файла
|
||
file_size = os.path.getsize(file_path) / (1024 * 1024) # Размер в мегабайтах
|
||
|
||
# Сохраняем данные о файле в базу данных
|
||
try:
|
||
await UploadedFileRepository.upload_file(
|
||
user_id=user_id,
|
||
user_name=user_name,
|
||
file_path=str(file_path).replace("\\", "/"),
|
||
file_name=file.filename,
|
||
file_type=file_type,
|
||
file_size=file_size
|
||
)
|
||
except Exception as e:
|
||
raise HTTPException(status_code=500, detail=f"Ошибка при сохранении данных в базе данных: {str(e)}")
|
||
|
||
return {"message": "Файл успешно загружен", "file_path": str(file_path), "file_size_MB": round(file_size, 2)}
|
||
|