Image Uploads
NotesThe cover image has been a basic URL so far, relying on you manually placing images under the static directory. Next, we need the ability to upload images. Fortunately, FastAPI provides UploadFile.
Like the database and TLS certificates, uploaded files are kept outside the project, in an external volume mounted using a soft link in development:
mkdir -p ~/volumes/uploadsIf not already, create a mnt directory in the root of your project:
mkdir -p mntAnd, within your project create a new soft link to the external uploads directory:
ln -s ~/volumes/uploads mnt/uploadsFor example, your project mnt directory might look something like this:
.
└── example-for-you
└── mnt
├── certs -> /home/<USERNAME>/volumes/certs
├── db -> /home/<USERNAME>/volumes/db
└── uploads -> /home/<USERNAME>/volumes/uploadsThis exercise is also a great candidate for some new settings for the location and path, which you might want to alter when deploying into different environments. It’s also worth adding the site’s domain name, for use in later sections, for example in links sent by email. Building up reusable settings makes the project more flexible, and when we come to deploying this application using a container, will pay dividends.
Add the following settings to config/settings.py:
CONF_MAIN_DOMAIN: str = "https://localhost" # NEW
CONF_IMAGE_UPLOADS_CONTEXT_PATH: str = "/uploads/" # NEW
CONF_IMAGE_UPLOADS_FILE_PATH: str = "mnt/uploads/" # NEWEvery setting needs a type annotation (: str). Without one, Pydantic v2 refuses to start, with PydanticUserError: A non-annotated attribute was detected.
We can mount this directory in the same way as the static directory earlier:
def configure_routing():
main_app.mount('/static', StaticFiles(directory='web/static'), name='static')
main_app.mount(settings.CONF_IMAGE_UPLOADS_CONTEXT_PATH.rstrip('/'), # NEW
StaticFiles(directory=settings.CONF_IMAGE_UPLOADS_FILE_PATH, check_dir=False), # NEW
name='uploads') # NEWcheck_dir=False lets the application start even if the uploads directory doesn’t exist yet, for example in a fresh clone or in tests. The directory is created the first time an image is saved.
Saving uploads safely#
Saving an upload is a little more involved than it first looks, because everything about it comes from the user’s browser, including the file name. Using that name directly, as in open(settings.CONF_IMAGE_UPLOADS_FILE_PATH + cover_image.filename, 'wb'), is dangerous: a crafted name like ../../main.py would write outside the uploads directory, and two posts with a cover.jpg would overwrite each other’s image.
So instead, generate a new, unique file name, and only allow image extensions. As this will be used for creating and updating posts, put it in a small helper module:
import shutil
import uuid
from pathlib import Path
from fastapi import HTTPException, UploadFile, status
from config.settings import settings
ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}
def save_cover_image(upload: UploadFile) -> str:
"""Save an uploaded cover image under a new, unique name. Returns its URL path."""
extension = Path(upload.filename or "").suffix.lower()
if extension not in ALLOWED_EXTENSIONS:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Please upload a JPEG, PNG or WebP image.")
# Never trust the uploaded file name: generate our own
filename = f"{uuid.uuid4()}{extension}"
upload_dir = Path(settings.CONF_IMAGE_UPLOADS_FILE_PATH)
upload_dir.mkdir(parents=True, exist_ok=True)
with open(upload_dir / filename, "wb") as file:
shutil.copyfileobj(upload.file, file)
return settings.CONF_IMAGE_UPLOADS_CONTEXT_PATH + filenameupload.file is the uploaded file itself, and shutil.copyfileobj copies it to disk in chunks, so a large upload isn’t read into memory all at once. The function returns the path where the image is served, for example /uploads/026fe355-1e85-4497-80c8-749fd8ff3ee4.png, which is what gets stored in the database. It’s a path rather than a full URL including the domain, so the same data works locally and when deployed.
Next, update the blogpost_create_post_view function to accept an UploadFile, and use the helper:
from fastapi import APIRouter, status, Request, Depends, Form, UploadFile, File # UPDATEDfrom web.images import save_cover_image # NEW@router.post('/blog/create', response_class=HTMLResponse)
def blogpost_create_post_view(*,
title: str = Form(...),
teaser: str = Form(...),
content: str = Form(...),
cover_image: UploadFile = File(...), # UPDATED
published: bool = Form(False),
session: Session = Depends(get_session_db)):
cover_image_path = save_cover_image(cover_image) # NEW
new_blogpost = BlogPostIn(title=title, teaser=teaser, content=content,
cover_image=cover_image_path, published=published) # UPDATED
post = create_blogpost_api(blogpost_in=new_blogpost, session=session)
return RedirectResponse(f'/blog/{post.id}', status_code=status.HTTP_303_SEE_OTHER)The view is a plain def, so it reads the upload with ordinary file operations. In an async def view you would use await cover_image.read() instead.
The create form needs to be updated to include enctype="multipart/form-data", which is how browsers send files:
<form action="/blog/create" enctype="multipart/form-data" method="post">Finally, update the form cover image field from type="text" to type="file", for example:
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Cover Image</label>
<input type="file" class="form-control" placeholder="Cover Image" id="cover_image"
name="cover_image" accept="image/png, image/jpeg, image/webp" required>
<p>(Image size 1900x600)</p>
<p class="help-block text-danger"></p>
</div>
</div>You should now have the ability to select a local image file and have it uploaded. The theme’s header works best with images of 1900x600, so the form suggests that size. The next section uses Pillow to enforce it, which at least avoids crazy large images being uploaded.
The same changes need applying to the update view and the blog_update.html template. However, we don’t want to force a user to always choose a new cover image, so for the update it’s optional. If no new file is chosen, the post keeps its current image, which the view reads from the database:
@router.post('/blog/update/{id}', response_class=HTMLResponse)
def blogpost_update_post_view(*,
id: uuid.UUID,
title: str = Form(...),
teaser: str = Form(...),
content: str = Form(...),
cover_image: UploadFile | None = File(None), # UPDATED
published: bool = Form(False),
session: Session = Depends(get_session_db)):
post = get_blogpost_by_id_api(id=id, session=session) # NEW
cover_image_path = post.cover_image # NEW
if cover_image and cover_image.filename: # NEW
cover_image_path = save_cover_image(cover_image) # NEW
blogpost_updates = BlogPostIn(title=title, teaser=teaser, content=content,
cover_image=cover_image_path, published=published) # UPDATED
update_blogpost_api(id=id, data=blogpost_updates, session=session)
return RedirectResponse(f'/blog/{id}', status_code=status.HTTP_303_SEE_OTHER)Taking the current image from the database, rather than from a hidden form field, means users can’t point a post at an arbitrary image by editing the form.
<form action="/blog/update/{{ context.post.id }}" enctype="multipart/form-data" method="post">Update the form cover image field from type="text" to an optional type="file", and show the current image:
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Cover Image</label>
<input type="file" class="form-control" placeholder="Cover Image" id="cover_image"
name="cover_image" accept="image/png, image/jpeg, image/webp">
<p>(Image size 1900x600)</p>
<small>Current image: {{ context.post.cover_image }}</small>
<p class="help-block text-danger"></p>
</div>
</div>Remember that blogpost.html already uses {{ context.post.cover_image }} for its header background, so uploaded images appear straight away.