Fred808 commited on
Commit
e09e77c
·
verified ·
1 Parent(s): 0765867

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -0
app.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from fastapi import FastAPI, UploadFile, File, HTTPException
3
+ from fastapi.responses import FileResponse, JSONResponse
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ import os
6
+ import uuid
7
+
8
+ app = FastAPI()
9
+
10
+ # Configure CORS
11
+ app.add_middleware(
12
+ CORSMiddleware,
13
+ allow_origins=["*"], # Allows all origins
14
+ allow_credentials=True,
15
+ allow_methods=["*"], # Allows all methods
16
+ allow_headers=["*"], # Allows all headers
17
+ )
18
+
19
+ UPLOAD_DIRECTORY = "./uploads"
20
+
21
+ os.makedirs(UPLOAD_DIRECTORY, exist_ok=True)
22
+
23
+ @app.post("/upload")
24
+ async def upload_mp4(file: UploadFile = File(...)):
25
+ if not file.filename.endswith(".mp4"):
26
+ raise HTTPException(status_code=400, detail="Invalid file type. Only MP4 files are allowed.")
27
+
28
+ file_id = str(uuid.uuid4()) + ".mp4"
29
+ file_path = os.path.join(UPLOAD_DIRECTORY, file_id)
30
+
31
+ try:
32
+ with open(file_path, "wb") as buffer:
33
+ while True:
34
+ chunk = await file.read(1024 * 1024) # Read in 1MB chunks
35
+ if not chunk:
36
+ break
37
+ buffer.write(chunk)
38
+ return JSONResponse(content={"id": file_id, "message": "File uploaded successfully"}, status_code=200)
39
+ except Exception as e:
40
+ raise HTTPException(status_code=500, detail=f"Failed to upload file: {str(e)}")
41
+
42
+ @app.get("/download/{mp4_id}")
43
+ async def download_mp4(mp4_id: str):
44
+ file_path = os.path.join(UPLOAD_DIRECTORY, mp4_id)
45
+ if not os.path.exists(file_path):
46
+ raise HTTPException(status_code=404, detail="File not found")
47
+ return FileResponse(file_path, media_type="video/mp4", filename=mp4_id)
48
+
49
+ @app.delete("/delete/{mp4_id}")
50
+ async def delete_mp4(mp4_id: str):
51
+ file_path = os.path.join(UPLOAD_DIRECTORY, mp4_id)
52
+ if not os.path.exists(file_path):
53
+ raise HTTPException(status_code=404, detail="File not found")
54
+ try:
55
+ os.remove(file_path)
56
+ return JSONResponse(content={"message": f"File {mp4_id} deleted successfully"}, status_code=200)
57
+ except Exception as e:
58
+ raise HTTPException(status_code=500, detail=f"Failed to delete file: {str(e)}")
59
+
60
+