NameIsJACK commited on
Commit
324bb3c
·
1 Parent(s): f009dd8

second commit

Browse files
Files changed (1) hide show
  1. main.py +29 -2
main.py CHANGED
@@ -1,5 +1,7 @@
1
  from fastapi import FastAPI, File, UploadFile
2
- from fastapi.responses import HTMLResponse
 
 
3
 
4
  app = FastAPI()
5
 
@@ -16,14 +18,39 @@ html_content = """
16
  <input name="file" type="file">
17
  <input type="submit">
18
  </form>
 
 
 
 
19
  </body>
20
  </html>
21
  """
22
 
23
  @app.get("/", response_class=HTMLResponse)
24
  async def read_root():
25
- return html_content
 
26
 
27
  @app.post("/uploadfile/")
28
  async def upload_file(file: UploadFile = File(...)):
 
 
 
 
 
 
 
 
29
  return {"filename": file.filename}
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from fastapi import FastAPI, File, UploadFile
2
+ from fastapi.responses import HTMLResponse, FileResponse
3
+ import shutil
4
+ import os
5
 
6
  app = FastAPI()
7
 
 
18
  <input name="file" type="file">
19
  <input type="submit">
20
  </form>
21
+ <h2>Uploaded Files</h2>
22
+ <ul>
23
+ {file_list}
24
+ </ul>
25
  </body>
26
  </html>
27
  """
28
 
29
  @app.get("/", response_class=HTMLResponse)
30
  async def read_root():
31
+ file_list = get_uploaded_files()
32
+ return html_content.format(file_list=file_list)
33
 
34
  @app.post("/uploadfile/")
35
  async def upload_file(file: UploadFile = File(...)):
36
+ # Save the uploaded file to the uploads directory
37
+ upload_directory = "uploads"
38
+ os.makedirs(upload_directory, exist_ok=True) # Create the directory if it doesn't exist
39
+ file_location = f"{upload_directory}/{file.filename}"
40
+
41
+ with open(file_location, "wb") as buffer:
42
+ shutil.copyfileobj(file.file, buffer)
43
+
44
  return {"filename": file.filename}
45
+
46
+ def get_uploaded_files():
47
+ upload_directory = "uploads"
48
+ files = os.listdir(upload_directory)
49
+ file_links = ""
50
+ for file in files:
51
+ file_links += f'<li><a href="/files/{file}">{file}</a></li>'
52
+ return file_links
53
+
54
+ @app.get("/files/{filename}")
55
+ async def get_file(filename: str):
56
+ return FileResponse(f"uploads/{filename}")