Skip to content

Commit

Permalink
Handle uploads
Browse files Browse the repository at this point in the history
  • Loading branch information
abhishekmj303 committed Apr 20, 2024
1 parent f949b47 commit 7b8676d
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 30 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
__pycache__
.venv
static/dist/
static/dist/
uploads
39 changes: 31 additions & 8 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import os
import shutil
import uuid
from typing import Annotated

from fastapi import FastAPI, Request, UploadFile
from fastapi import Cookie, FastAPI, Request, UploadFile
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
Expand All @@ -11,12 +14,32 @@


@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
async def read_root(
request: Request,
user_id: Annotated[str | None, Cookie()] = None,
):
response = templates.TemplateResponse("index.html", {"request": request})
print(f"User ID: {user_id}")
if user_id is None:
user_id = str(uuid.uuid4())
response.set_cookie(key="user_id", value=user_id, httponly=True)
print(f"Set cookie: {user_id}")
return response


@app.post("/upload/", response_class=HTMLResponse)
async def create_upload_file(request: Request, file: UploadFile):
with open(f"static/{file.filename}", "wb") as buffer:
buffer.write(await file.read())
return templates.TemplateResponse("upload.html", {"request": request})
@app.post("/upload/")
async def create_upload_file(
request: Request,
user_id: Annotated[str, Cookie()],
files: list[UploadFile],
):
print(f"User ID: {user_id}")
print({"filenames": [file.filename for file in files]})
if os.path.exists(f"uploads/{user_id}"):
shutil.rmtree(f"uploads/{user_id}")
os.makedirs(f"uploads/{user_id}", exist_ok=True)
for i, file in enumerate(files):
file_path = f"uploads/{user_id}/{i}_{file.filename}"
with open(file_path, "wb") as buffer:
buffer.write(await file.read())
return ""
58 changes: 37 additions & 21 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,27 +25,35 @@
<div class="flex flex-col items-center justify-center h-screen bg-gray-100">
<div class="p-6 bg-white rounded-lg shadow-md">
<h1 class="text-2xl font-bold mb-4">Document Scanner</h1>
<input type="file" name="filepond" class="filepond">
<div class="flex flex-col space-y-4">
<button class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-gray-100 hover:text-accent-foreground h-10 px-4 py-2 transition-transform duration-300 hover:scale-105">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="mr-2 h-5 w-5"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="17 8 12 3 7 8"></polyline>
<line x1="12" x2="12" y1="3" y2="15"></line>
</svg>
Upload Photos
</button>
<form id='form'
hx-encoding='multipart/form-data'
hx-post='/upload'
hx-swap="none"
hx-on::after-request="if(event.detail.successful) this.reset()">
<input type="file" name="files" class="filepond" required>
<div class="flex flex-col space-y-4">
<progress id='progress' value='0' max='100'></progress>
<button class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-gray-100 hover:text-accent-foreground h-10 px-4 py-2 transition-transform duration-300 hover:scale-105"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="mr-2 h-5 w-5"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="17 8 12 3 7 8"></polyline>
<line x1="12" x2="12" y1="3" y2="15"></line>
</svg>
Upload Photos
</button>
</form>
<!-- <div class="htmx-indicator">Uploading...</div> -->
<span class="text-center text-gray-500">or</span>
<button class="inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-gray-100 hover:text-accent-foreground h-10 px-4 py-2 transition-transform duration-300 hover:scale-105">
Expand Down Expand Up @@ -92,7 +100,15 @@ <h1 class="text-2xl font-bold mb-4">Document Scanner</h1>
const pond = FilePond.create(inputElement, {
allowMultiple: true,
allowReorder: true,
storeAsFile: true,
acceptedFileTypes: ['image/jpeg', 'image/png', 'image/jpg'],
credits: false
});
</script>

<script>
htmx.on('#form', 'htmx:xhr:progress', function(evt) {
htmx.find('#progress').setAttribute('value', evt.detail.loaded/evt.detail.total * 100)
});
</script>
{% endblock %}

0 comments on commit 7b8676d

Please sign in to comment.