File size: 1,552 Bytes
9ec2d3e
324bb3c
 
 
9ec2d3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324bb3c
 
 
 
9ec2d3e
 
 
 
 
 
324bb3c
 
9ec2d3e
 
 
324bb3c
 
 
 
 
 
 
 
9ec2d3e
324bb3c
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse, FileResponse
import shutil
import os

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(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)

    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}")