testSpaceupload / main.py
NameIsJACK's picture
comeon
7e370cd
from fastapi import FastAPI, File, UploadFile, BackgroundTasks
from fastapi.responses import HTMLResponse, FileResponse
import shutil
import os
import time
app = FastAPI()
# HTML form for file upload
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h2>Upload a File</h2>
<form action="/uploadfile/" method="post" enctype="multipart/form-data">
<input name="file" type="file">
<input type="submit">
</form>
<h2>Uploaded Files</h2>
<ul>
{file_list}
</ul>
</body>
</html>
"""
@app.get("/", response_class=HTMLResponse)
async def read_root():
file_list = get_uploaded_files()
return html_content.format(file_list=file_list)
@app.post("/uploadfile/")
async def upload_file(background_tasks: BackgroundTasks,file: UploadFile = File(...)):
# Save the uploaded file to the uploads directory
upload_directory = "uploads"
os.makedirs(upload_directory, exist_ok=True) # Create the directory if it doesn't exist
file_location = f"{upload_directory}/{file.filename}"
with open(file_location, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# Schedule the file deletion after 10 minutes
background_tasks.add_task(delete_file_after_delay, file_location, 600) # 600 seconds = 10 minutes
return {"filename": file.filename}
def get_uploaded_files():
upload_directory = "uploads"
files = os.listdir(upload_directory)
file_links = ""
for file in files:
file_links += f'<li><a href="/files/{file}">{file}</a></li>'
return file_links
@app.get("/files/{filename}")
async def get_file(filename: str):
return FileResponse(f"uploads/{filename}")
def delete_file_after_delay(file_path: str, delay: int):
time.sleep(delay) # Wait for the specified delay
if os.path.exists(file_path):
os.remove(file_path) # Delete the file
print(f"Deleted file: {file_path}") # Log the deletion (optional)