Kitten

Explore Kitten’s built-in support for multi-part forms and file uploads as you build a simple image upload example.

Topics covered

Kitten has high-level support for multi-part form handling and file uploads.

Uploads sent via <input type='file'> in your pages to a POST route that requires sign-in are saved in kitten.paths.APP_UPLOADS_DIRECTORY, the uploads folder in kitten.paths.APP_DATA_DIRECTORY. Kitten assigns them unique IDs and serves them from the /uploads/<unique-id>/ route. The Upload objects are available to those routes in the request.uploads array, which is empty when the request doesn’t contain a file.

Uploads are private by default: Kitten serves an upload only to you, once you’re signed in. To show an upload to everyone (e.g., an image in a public gallery), set its public property to true in your POST route.

An upload object has the following properties:

.id           // Unique id. Used to look up uploads and calculate resource paths.
.fileName     // Name of the original file that was uploaded.
.filePath     // Absolute path to uploaded file on server.

.resourcePath // Absolute URL path the upload is served from: /uploads/<id>/.
.downloadPath // Absolute URL path that downloads the upload: /uploads/<id>/download/.
              // A PNG, JPEG, GIF, WebP, or AVIF image, audio, video, or plain text opens inline; any other upload downloads.

.public       // Whether Kitten serves the upload to anyone (true) or only to you, signed in (false, the default).

.mimetype     // MIME type of file.
.field        // Name of file upload field in form that file was uploaded from.
.encoding     // Transfer encoding of the file’s part of the form, e.g., 7bit.
.truncated    // Always false. Kitten deletes a file over the size limit.
.done         // Whether the file has been written to disk (boolean).

And the following method:

.delete()     // Deletes the upload.

A common idiom is to save the upload’s unique ID (e.g., request.uploads[0].id), along with any other data in your form (e.g., the alt-text of an image upload), in your own database tables. Then, when you want to, say, render an uploaded image on a page, you can use the global kitten.uploads object to reference the upload you need and access its resource path.

e.g.,

kitten.html`
  <img src='${kitten.uploads.get(uploadId)?.resourcePath}' alt='…'>
`

The kitten.uploads collection has the following methods:

.get(id)    // Returns Upload object with given ID (or undefined, if it doesn’t exist).
.length()   // Returns the number of uploads.
.all()      // Returns array of all Upload objects.
.allIds()   // Returns array of strings of all Upload object IDs.
.delete(id) // Deletes object with given id (or fails silently if it doesn’t exist).

Kitten can handle multiple file uploads as well as single ones.

Note that you must set the enctype='multipart/form-data' attribute on your forms for file uploads to work correctly.

The following basic example shows just how easy it is to handle file uploads in Kitten. In it, you can upload one image at a time along with its alt-text, and a public gallery at / displays them in a grid.

Uploads require sign-in, so the upload form and its POST route are in an upload🔒/ folder, which responds at /upload/. The gallery is public, so the POST route makes each upload public. (See Uploads in the reference.)

kitten.db.images ??= []

export default () => kitten.html`
<h1>Image gallery</h1>

<if ${kitten.db.images.length === 0}><p>No images yet.</p></if>

<ul>
  ${kitten.db.images.map(image => kitten.html`
    <li><img src=${image.path} alt=${image.altText}></li>
  `)}
</ul>

<a href='/upload/'>Upload an image</a>
`
kitten.db.images ??= []

export default function ({ request, response }) {
  request.uploads.forEach(upload => {
    upload.public = true
    kitten.db.images.push({
      path: upload.resourcePath,
      altText: request.body.altText ? request.body.altText : upload.fileName
    })
  })
  response.get('/upload/')
}
kitten.db.images ??= []

export default () => kitten.html`
<h2>Uploaded images</h2>

<if ${kitten.db.images.length === 0}><p>None yet.</p></if>

<ul>
  ${kitten.db.images.map(image => kitten.html`
    <li><img src=${image.path} alt=${image.altText}></li>
  `)}
</ul>

<h2>Upload an image</h2>

<form method='post' enctype='multipart/form-data'>
  <label for='image'>Image</label>
  <input type='file' id='image' name='image' accept='image/*'>
  <label for='alt-text'>Alt text</label>
  <input type='text' id='alt-text' name='altText'>
  <button type='submit'>Upload</button>
</form>

<style>
  body { max-width: 640px; margin: 0 auto; padding: 1em; font-family: sans-serif; }
  ul { padding: 0; display: grid; grid-template-columns: 1fr 1fr; }
  img { max-height: 30vh; margin: 1em; }
  input { width: 100%; margin: 1em 0; }
  button { padding: 0.25em 1em; display: block; margin: 0 auto; }
</style>
`

You can find the code for the above example in the examples/file-uploads folder of the Kitten source code. There is also an Ajax version of the example in examples/file-uploads-ajax and a Streaming HTML version in examples/streaming-html/file-uploads

When a request exceeds the kitten.uploadLimits.fileSize, files, fieldSize, or body limit, Kitten deletes all files in it and responds with its 413 page. To show the person an error in your own page instead, export onUploadLimit from your POST route.

In the Ajax version of the example, the hook returns the form with an error and the alt text the person entered, and htmx swaps it into the page:

export function onUploadLimit ({ request, limit }) {
  const error = limit.name === 'fileSize' ? `The image must be ${limit.value / 1_000_000} MB or smaller.` : 'The upload is too large.'
  return kitten.html`<${images} error=${error} altText=${request.body.altText ?? ''} />`
}

The request.body object contains the fields that arrived before the limit, so the form places its alt text field before its file input. See onUploadLimit in the reference for the other ways to respond.

A route can also set its own limits by exporting uploadLimits, which replace the ones in the kitten.uploadLimits object for requests to that route. The upload limits example has a form for small images whose route limits each image to 100 KB. (See uploadLimits in the reference.)

Now that you know how to work with multi-part forms and file uploads, let’s return to the Fetchiverse example and extend it to create a streaming interface of curated public fediverse posts using Kitten’s first-class support for Hypermedia-driven application development using htmx, the htmx WebSocket extension, and Kitten’s socket routes (.socket.js files).

Next tutorial: htmx, the htmx WebSocket extension, and socket routes

Like this? Fund us!

Small Technology Foundation is a tiny, independent not-for-profit.

We exist in part thanks to patronage by people like you. If you share our vision and want to support our work, please become a patron or donate to us today and help us continue to exist.