Reference sections
Reference āŗ Uploads
Kitten automatically saves files sent from a multipart form (enctype='multipart/form-data') that contains a file input (<input type='file'>) to a POST route that requires sign-in (š) or exports authorise.
Files are stored in kitten.paths.APP_UPLOADS_DIRECTORY which refers to the uploads folder in kitten.paths.APP_DATA_DIRECTORY.
Kitten saves files only for a POST to a route that requires sign-in (š), whether it is your appās or one of Kittenās own, and for a POST to a public route that exports authorise. A visitor who isnāt signed in is redirected to sign in before Kitten reads the request body. A multipart request to any other public route has its fields parsed into request.body and its files discarded, so the request.uploads array is empty, and the request.discardedFiles property is the number of files Kitten discarded. (Note that a public route without authorise cannot take uploads even with its own code, as Kitten parses the request body before your routeās default export runs.)
A public route still receives a body that is not multipart (e.g., a JSON body or a webhook payload), up to its body limit, as request.rawBody, and parsed into request.body when it is JSON or URL-encoded.
An upload is private by default: Kitten serves it only to you, once youāre signed in. To show an upload to everyone, make it public (see Private and public uploads).
The kitten.uploadLimits object sets the limits applied to requests that have a body.
The defaults:
fileSize: 20 MB (20,000,000 bytes) per file.files: 10 files.fields: 1,000 fields in a form, multipart or URL-encoded. Minimum: 1.fieldSize: 1 MB (1,000,000 bytes) per field value.fieldNameSize: 100 bytes per field name in a URL-encoded form.body: 4 MB (4,000,000 bytes) per request, not counting files. For a multipart form the limit applies to the aggregate size of its field values. For any other request (URL-encoded form, JSON body, webhook payload) it applies to the size of the body.
If a request exceeds any of the limits, Kitten deletes all files in the request. Unless the route responds through its onUploadLimit hook, Kitten responds with its 413 Payload Too Large page and logs the limit:
ā 413 on POST /upload/: a file is larger than the limit (Kittenās default fileSize limit is 20,000,000 bytes). Export onUploadLimit from uploadš/index.post.js to respond.
The line mentions where the limit that the request exceeded is set: the routeās uploadLimits export (e.g., uploadLimits.fileSize in uploadš/small/index.post.js), the kitten.uploadLimits object (e.g., kitten.uploadLimits.fileSize), or Kittenās default, as above. Kitten adds the last sentence of that line only for a fileSize, files, fieldSize, or body limit on one of your appās POST routes.
A POST route that requires sign-in or exports authorise can respond to the fileSize, files, fieldSize, and body limits itself by exporting onUploadLimit. On any other POST route, the onUploadLimit hook runs for the files, fieldSize, and body limits, and never for the fileSize limit. Kitten always responds with its 413 page to the fieldNameSize and fields limits. Only your formās markup, or a crafted request, can exceed those.
Kitten responds with 404 to a request over a limit to a path with no route.
When Kitten cannot parse a form or if it is sent a JSON body that is not JSON, it returns a 400 Bad Request response. If a URL-encoded body is sent in a charset other than UTF-8 or Latin-1 Kitten returns a 415 Unsupported Media Type error response. These responses are sent before your routeās default export runs.
To change a limit, set your custom value in main.script.js, e.g.,
kitten.uploadLimits.fileSize = 50_000_000
You can also change all limits by assigning kitten.uploadLimits to an object.
Infinity removes a limit. A limit you leave out, or set to something other than a number (including NaN), takes Kittenās default.
Each limit must be a whole number or Infinity, and the fields limit must be at least 1. Kitten checks the kitten.uploadLimits object once main.script.js has run. If a limit breaks these rules, Kitten stops at start-up with a line that mentions the limit and its value. If a key isnāt a limit (e.g., filesize), Kitten stops with a line that mentions the key and lists the limits.
Kitten reads the limits on every request, so a change made while the server is running will apply starting with the next request. (If you change a limit to a value that breaks the rules above while the server is running, each request whose body Kitten parses fails instead.)
An HTTP route can set its own limits by exporting uploadLimits, a plain object with any of the limits in kitten.uploadLimits. Each limit it sets replaces the one in the kitten.uploadLimits object for requests to that route. The others come from the kitten.uploadLimits object, and then from Kittenās defaults. A limit in the uploadLimits export that isnāt a number (including NaN) is the same as one you leave out.
This uploadš/small/index.post.js route, from the upload limits example, limits each image to 100 KB, while the exampleās main.script.js sets the kitten.uploadLimits.fileSize limit to 1 MB for its other routes:
kitten.db.images ??= []
export const uploadLimits = { fileSize: 100_000 }
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/')
}
export function onUploadLimit ({ request, response, limit }) {
const error = limit.name === 'fileSize' ? 'file-too-large' : 'upload-too-large'
response.get(`/upload/small/?error=${error}&altText=${encodeURIComponent(request.body.altText ?? '')}`)
}
Kitten checks a routeās uploadLimits export by the same rules as the kitten.uploadLimits object when the route loads. If a limit breaks the rules, the route fails to load with a line that mentions the limit, its value, and the routeās file. If a key isnāt a limit, the line mentions the key and the file and lists the limits. If the export isnāt a plain object, the line mentions the file.
Kittenās own restore route (/š/data/restore/) exports uploadLimits = { fileSize: Infinity }, so you can restore a backup that is larger than the kitten.uploadLimits.fileSize limit.
In a POST route, request.uploads is an array of Upload objects, one per file. Itās empty when the request does not include a file, and always empty in a public route without authorise.
Each Upload object has the following properties:
id: the uploadās unique ID.fileName: the name of the file on the personās computer.filePath: where the file is stored on disk.mimetype: the fileās MIME type.encoding: the transfer encoding of the file, e.g.,7bit.field: the name of the form field the file originated from.truncated: alwaysfalse. Kitten deletes a file over thekitten.uploadLimits.fileSizelimit and either runs the routeāsonUploadLimithook or responds with 413.done:trueonce the file is written to disk.resourcePath:/uploads/<id>/, where Kitten serves the file inline when its type isimage/png,image/jpeg,image/gif,image/webp,image/avif, audio, video, ortext/plain, and as a download otherwise.downloadPath:/uploads/<id>/download/, where Kitten serves the file as a download.public:truewhen Kitten serves the upload to anyone, andfalse(the default) when it serves it only to you, signed in. See Private and public uploads.delete(): deletes the file from disk and removes it from thekitten.uploadsobject.
Every upload is served with the Content-Security-Policy: sandbox header. An upload whose type is not on that list downloads when its URL is opened; one shown in an <img>, <video>, or <audio> element displays as before.
Kitten serves an upload with the Accept-Ranges: bytes and Content-Length headers, responds to a Range request for one range with 206 Partial Content and those bytes, to an unsatisfiable one with 416 Range Not Satisfiable, and to a HEAD request with the headers alone. A <video> or <audio> element can seek in an upload.
An upload is private by default. Kitten serves a private upload only to you, once youāre signed in, with the Cache-Control: private header and no Access-Control-Allow-Origin header. Anyone else is redirected to the sign-in page, as for a š page. This ensures that a file you upload (e.g., a backup, or a draft) isnāt public to anyone who learns its URL.
To serve an upload to anyone, set its public property to true in your POST route. Kitten persists it in its internal database and serves a public upload to anyone, with the Access-Control-Allow-Origin: * header. The public property must be exactly true, so a form fieldās 'true', which is a string, leaves the upload private.
This uploadš/index.post.js route, from the file uploads example, makes each image public, as the example shows its images in a public gallery:
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/')
}
Note that uploads stored by earlier versions of Kitten are public. (The first time Kitten opens its internal database after the upgrade, it marks every existing upload public, except backup archives left in the uploads store by a restore, which contain Kittenās internal database.)
A POST route can export onUploadLimit next to its default handler. Kitten calls it in place of the default handler for a request over the fileSize, files, fieldSize, or body limit (on a route that doesnāt store files, never for fileSize):
export default function ({ request, response }) {
// Kitten never calls this for a request over a limit.
}
export function onUploadLimit ({ request, response, limit }) {
// limit is { name, value }.
}
limit.name:fileSize,files,fieldSize, orbody.limit.value: the value of that limit for the route: from itsuploadLimitsexport, from thekitten.uploadLimitsobject, or Kittenās default.request.body: the form fields that arrived complete before the limit, and{}for any other body. For afileSizeorfileslimit, it contains all text fields that come before the file input.request.uploads: always empty.
Kitten sends the return value of the onUploadLimit hook as it sends a routeās return value, with status 200 unless the hook sets another. htmx does not swap a 4xx response by default. To send 413, call response.withCode(413, ā¦).
Kitten responds with its 500 page to all requests to a route whose onUploadLimit export is not a function.
Kitten does not process <page> directives in markup a POST route returns. A hook can respond in three ways:
With Streaming HTML, the hook emits an event on the session and the page sends the error over its WebSocket:
// uploadš/index.post.js
export function onUploadLimit ({ request, response, limit }) {
request.session.emit('uploadLimitExceeded', limit)
response.ok()
}
// uploadš/index.page.js
export function onConnect () {
this.addSessionEventHandler('uploadLimitExceeded', limit => {
const message = limit.name === 'fileSize' ? `The image must be ${limit.value / 1_000_000} MB or smaller.` : 'The upload is too large.'
this.send(kitten.html`<${status}>ā ${message}</>`)
})
}
With htmx, the hook returns the form with the error and the fields the person entered, and htmx swaps it in:
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 ?? ''} />`
}
With a plain form, the hook redirects to the page with an error code, and the page renders the sentence for that code (Post/Redirect/Get):
export function onUploadLimit ({ request, response, limit }) {
const error = limit.name === 'fileSize' ? 'file-too-large' : 'upload-too-large'
response.get(`/upload/?error=${error}&altText=${encodeURIComponent(request.body.altText ?? '')}`)
}
See the Streaming HTML file uploads, file uploads with Ajax, and upload limits examples.
The kitten.uploads object contains all uploads made to a POST route that requires sign-in or exports authorise, keyed by ID, in Kittenās internal database:
get(id): returns theUploadobject with the given ID, orundefinedwhen there is none.length(): returns the number of uploads.all(): returns an array of everyUploadobject.allIds(): returns an array of every upload ID.delete(id)(async): deletes the file from disk and removes the upload.
For example, this uploadš/index.post.js route saves the path of every uploaded image in the default database and redirects back to the upload page, /upload/:
kitten.db.images ??= []
export default function ({ request, response }) {
request.uploads.forEach(upload => {
kitten.db.images.push({
path: upload.resourcePath,
altText: request.body.altText ? request.body.altText : upload.fileName
})
})
response.get('/upload/')
}
See the multipart forms and file uploads tutorial, and the file uploads, file uploads with Ajax and Streaming HTML file uploads examples.