File Upload
Dotpress includes built-in support for file uploads, with automatic validation of file size, MIME type, and extensions.
1. Install multer
We use the popular express library Multer for handling files.
npm i multer
2. Declare accepted files in your route handler
defineRoute({
method: 'post',
path: '/profile/upload',
files: {
avatar: {
maxSize: 5 * 1024 * 1024, // 5MB
mimeTypes: ['image/jpeg', 'image/png'],
extensions: ['.jpg', '.jpeg', '.png']
}
},
handler: async ({ getFile }) => {
// Use the getFile helper to access uploaded file object
const avatarFile = getFile('avatar');
return { fileName: avatarFile?.originalname };
}
});
Note that the 3 validation properties maxSize, mimeTypes and extensions are optional. However, we strongly recommend always validating the file size as well as the extension or MIME type.
If validation fails, the application will return a 400 Bad Request response.