VS6 / app.py
Fred808's picture
Create app.py
e09e77c verified
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import FileResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import os
import uuid
app = FastAPI()
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
)
UPLOAD_DIRECTORY = "./uploads"
os.makedirs(UPLOAD_DIRECTORY, exist_ok=True)
@app.post("/upload")
async def upload_mp4(file: UploadFile = File(...)):
if not file.filename.endswith(".mp4"):
raise HTTPException(status_code=400, detail="Invalid file type. Only MP4 files are allowed.")
file_id = str(uuid.uuid4()) + ".mp4"
file_path = os.path.join(UPLOAD_DIRECTORY, file_id)
try:
with open(file_path, "wb") as buffer:
while True:
chunk = await file.read(1024 * 1024) # Read in 1MB chunks
if not chunk:
break
buffer.write(chunk)
return JSONResponse(content={"id": file_id, "message": "File uploaded successfully"}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to upload file: {str(e)}")
@app.get("/download/{mp4_id}")
async def download_mp4(mp4_id: str):
file_path = os.path.join(UPLOAD_DIRECTORY, mp4_id)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="File not found")
return FileResponse(file_path, media_type="video/mp4", filename=mp4_id)
@app.delete("/delete/{mp4_id}")
async def delete_mp4(mp4_id: str):
file_path = os.path.join(UPLOAD_DIRECTORY, mp4_id)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="File not found")
try:
os.remove(file_path)
return JSONResponse(content={"message": f"File {mp4_id} deleted successfully"}, status_code=200)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to delete file: {str(e)}")