Docs/Features
File Uploads
- Define a files DTO:
import { fileUploadProperty } from 'alado';
export class UserFilesDto {
@fileUploadProperty({
mimetypes: ['image/png'],
maxSize: 1048576, // 1MB
required: true,
maxSizeError: {
statusCode: 413,
message: 'Max size is 1MB',
},
mimetypeError: {
statusCode: 415,
message: 'Only PNG allowed',
},
requiredError: {
statusCode: 400,
message: 'File is required',
},
})
avatar: string = '';
}- Use in controller:
import { createWriteStream } from 'fs';
@post('/user/:id/avatar', { tags: ['User'] })
@withAuth(bearerAuth)
@defineRequest({ path: Id, files: UserFilesDto })
setAvatar(req) {
const { avatar } = req.files;
// avatar: UploadedFile = { stream: Readable, size: number, mimetype: string, filename: string }
const writeStream = createWriteStream(`./uploads/user-${req.path.id}.png`);
avatar.stream.pipe(writeStream);
return {
statusCode: 202,
headers: { 'Content-Type': 'application/json' },
body: { message: 'Upload accepted' },
};
}How an upload is read
- The multipart body is read into one Buffer, and each file's content is a view into it (no copy). The body is held once in memory, so
maxBodySizeBytesmust cover the largest upload, and it is the bound on memory per request. Raise it on the upload route only (@post('/upload', { maxBodySizeBytes: 20 * 1024 * 1024 })) rather than for the whole server: memory for uploads is about that limit times the uploads running at once. - A body is read whole or not at all: one without a
boundaryparameter, without its first delimiter or cut off before the close delimiter (--boundary--) gets400 Malformed multipart bodyinstead of the parts that arrived. An empty body is an empty form. - A body may hold at most
parsing.maxPartsparts, text fields and files together (default 1000,0for no limit); more gets400 Too many multipart partsbefore any field is built. - A part's name and file name are read from its
Content-Dispositionheader only; another header (X-Anything: ; name="admin") cannot rename it. - Fields and files sent empty are kept (
''and a file of size0). A file input left empty (filename=""with no content) is skipped. filenameis the name the client sent, decoded as UTF-8, without its directories:../../etc/passwdispasswd,C:\Users\me\cv.pdfiscv.pdf, and.or..is''. Control characters (U+0000–U+001F, U+007F–U+009F: NUL, line breaks, tabs, terminal escapes) are removed from it and from the field name (3.9.6), so neither can break a file system call or rewrite a log line. Nothing else is checked (it may still be empty, very long, or hold characters your file system refuses), so never use it as a path as it is (the example above builds its own).mimetypeis the part's media type alone, lower-cased (Text/Plain; charset=utf-8istext/plain), and is compared withmimetypesthat way.- A file part without a
Content-Typeis kept asapplication/octet-stream, so only a field whosemimetypesinclude that type accepts it. - A text field sent twice, or as
name[], gives an array, as in a query string or a urlencoded form. - A file part under a name the route does not declare is skipped while the body is parsed.
req.rawBodyis still the body as text for multipart requests, but it is built only when you read it, since it costs as much memory again.
Several files in one field
One file per field name by default. A request may carry one file under each file field name. A second file under the same name (
<input type="file" multiple>,docs[]sent twice) is refused with400 Too many files under one field name, before any of the files is processed. Accepting several files is an explicit choice: setparsing: { maxFilesPerField: n }in the server options (0for no limit). Text fields are not limited per name; the parts of a whole body are, byparsing.maxParts.
When maxFilesPerField allows several files, parsing.repeatedFiles says how they are given: 'last' (default) keeps the last one; 'array' gives an array of every file in the order sent (also for one file sent as name[]), and each file is checked against the field's rules.
initializeApplication({
serverOptions: { port: 3000, parsing: { maxFilesPerField: 10, repeatedFiles: 'array' } },
controllers: [DocumentController],
});
@post('/documents')
@defineRequest({ files: DocumentFilesDto })
upload(req: Request) {
const files = req.files.docs as unknown as UploadedFile[] | UploadedFile;
for (const file of Array.isArray(files) ? files : [files]) {
// file.filename, file.mimetype, file.size, file.stream
}
return { statusCode: 204 };
}The Request type keeps one UploadedFile per field, so a field that can repeat is cast as above. A single file sent without [] stays a single object.
- Respond with Stream:
@get('/user/:id/avatar', { tags: ['User'] })
@withAuth(bearerAuth)
@defineResponse({
statusCode: 200,
title: 'OK',
headers: { 'Content-Type': 'image/png' },
body: {},
})
@defineRequest({ path: Id })
public getAvatar(req: Request) {
const readStream = createReadStream(`./uploads/user-${req.path.id}.png`);
return {
statusCode: 200,
headers: { 'Content-Type': 'image/png' },
body: readStream,
};
}