tempuploader / app.py
triflix's picture
Update app.py
bba27fd verified
from fastapi import FastAPI, UploadFile, File, BackgroundTasks
from fastapi.responses import HTMLResponse, FileResponse
import shutil
import os
import uuid
from pathlib import Path
import time
app = FastAPI()
TEMP_DIR = Path("/tmp/uploads")
TEMP_DIR.mkdir(parents=True, exist_ok=True)
# Background cleanup: delete files older than 1 hour
def cleanup_old_files():
now = time.time()
for f in TEMP_DIR.iterdir():
if now - f.stat().st_mtime > 3600:
try:
f.unlink()
except Exception:
pass
@app.get("/", response_class=HTMLResponse)
async def main():
html_path = Path(__file__).parent / "static" / "index.html"
return HTMLResponse(content=html_path.read_text(), status_code=200)
@app.post("/upload")
async def upload_temp_file(
background_tasks: BackgroundTasks,
file: UploadFile = File(...),
):
# Schedule cleanup task
background_tasks.add_task(cleanup_old_files)
unique_name = f"{uuid.uuid4()}_{file.filename}"
dest_path = TEMP_DIR / unique_name
with dest_path.open("wb") as buf:
shutil.copyfileobj(file.file, buf)
return {"filename": unique_name, "url": f"/files/{unique_name}"}
@app.get("/files/{filename}")
async def serve_file(filename: str):
file_path = TEMP_DIR / filename
if not file_path.exists():
return {"error": "File not found"}
return FileResponse(path=str(file_path), filename=filename)