DOCUMENTATION / API & OPERATIONS

File uploads

A file upload uses an HTML form with multipart/form-data. This lesson shows both a browser upload and a terminal request.

1. Create the upload form

<form action="/uploads" method="post" enctype="multipart/form-data">
  <label>Choose an image
    <input type="file" name="photo" accept="image/png,image/jpeg" required>
  </label>
  <button type="submit">Upload</button>
</form>

The enctype setting is required: otherwise the browser does not send the file as a multipart upload.

2. Register the upload page

def upload_page(req: Request) -> Response:
    return Response.html("""
    <form action="/uploads" method="post" enctype="multipart/form-data">
      <input type="file" name="photo" required>
      <button>Upload</button>
    </form>
    """)

Register app.get("/uploads", upload_page). A separate POST handler at the same URL must receive and store the file using Mojara's multipart upload interface.

3. Send a file from your terminal

curl -i -X POST http://127.0.0.1:8000/uploads \
  -F "photo=@./picture.jpg;type=image/jpeg"

The -F flag sends multipart form data. photo matches the form input name.

4. Validate before storing

The POST handler should reject absent files, files larger than the configured limit and disallowed media types. Use a generated server-side filename instead of trusting the submitted filename.

For private files, store outside the public static directory and verify the user's permission on every download. Return 413 for oversized requests, 415 for unsupported types, and 201 after a successful upload.

5. Upload multiple images

<input type="file" name="photos" accept="image/*" multiple>

The multiple attribute lets the browser send several files. The server should validate the combined request size and each file individually before saving them.