File size: 1,716 Bytes
970eef1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from fastapi import APIRouter, UploadFile, File
import os
import shutil
import uuid

router = APIRouter(tags=["files"])

# Définir le stockage des fichiers par session (importé dans main.py)
session_files = {}

# Dossier racine pour les uploads
UPLOAD_ROOT = "uploaded_files"
os.makedirs(UPLOAD_ROOT, exist_ok=True)

@router.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    """
    Upload a file to the server and generate a session ID
    
    Args:
        file: The file to upload
        
    Returns:
        Dictionary with filename, status and session_id
    """
    # Vérifier si le fichier est un PDF, TXT, HTML ou MD
    if not file.filename.endswith(('.pdf', '.txt', '.html', '.md')):
        return {"error": "Only PDF, TXT, HTML and MD files are accepted"}
    
    # Generate a session ID for this file
    session_id = str(uuid.uuid4())
    
    # Create the session directory structure
    session_dir = os.path.join(UPLOAD_ROOT, session_id)
    uploaded_files_dir = os.path.join(session_dir, "uploaded_files")
    os.makedirs(uploaded_files_dir, exist_ok=True)
    
    # Create the full path to save the file
    file_path = os.path.join(uploaded_files_dir, file.filename)
    
    # Sauvegarder le fichier
    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)
    
    # Store file path for later use
    session_files[session_id] = file_path
    
    # Débogage pour vérifier l'état des session_files
    print(f"DEBUG UPLOAD: File uploaded with session_id: {session_id}")
    print(f"DEBUG UPLOAD: Current session_files: {session_files}")
    
    return {"filename": file.filename, "status": "uploaded", "session_id": session_id}