Spaces:
Running
Running
File size: 1,426 Bytes
c6706bd |
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 53 54 55 56 57 58 59 |
"""File handling utilities"""
import os
import shutil
from pathlib import Path
from datetime import datetime
UPLOAD_DIR = "uploads"
def ensure_upload_dir():
"""Ensure uploads directory exists"""
Path(UPLOAD_DIR).mkdir(exist_ok=True)
def save_uploaded_file(file_content: bytes, original_filename: str) -> str:
"""
Save uploaded file with timestamp to ensure uniqueness.
Args:
file_content: File bytes
original_filename: Original filename
Returns:
Saved filename
"""
ensure_upload_dir()
# Generate unique filename with timestamp
timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S_%f")[:-3]
name, ext = os.path.splitext(original_filename)
saved_filename = f"{name}_{timestamp}{ext}"
filepath = os.path.join(UPLOAD_DIR, saved_filename)
# Write file
with open(filepath, "wb") as f:
f.write(file_content)
return saved_filename
def get_file_path(filename: str) -> str:
"""Get full path for a saved file"""
return os.path.join(UPLOAD_DIR, filename)
def file_exists(filename: str) -> bool:
"""Check if a saved file exists"""
return os.path.exists(get_file_path(filename))
def delete_file(filename: str) -> bool:
"""Delete a saved file"""
filepath = get_file_path(filename)
if os.path.exists(filepath):
os.remove(filepath)
return True
return False |