Upload and Download Files
Files can be uploaded and downloaded using FoalTS file system. It allows you to use different types of file storage such as the local file system or cloud storage.
Configuration
First install the package.
npm install @foal/storage
Then specify in your configuration the file storage to be used and its settings. In this example, we will use the local file system with the uploaded
directory (you must create it at the root of your project).
- YAML
- JSON
- JS
settings:
disk:
driver: 'local'
local:
directory: 'uploaded'
{
"settings": {
"disk": {
"driver": "local",
"local": {
"directory": "uploaded"
}
}
}
}
module.exports = {
settings: {
disk: {
driver: "local",
local: {
directory: "uploaded"
}
}
}
}
File Uploads
Files can be uploaded using multipart/form-data
requests. The @ParseAndValidateFiles
hook parses the request body, validates the submitted fields and files and save them in streaming to your local or Cloud storage. It also provides the ability to create file buffers if you wish.
The enctype
of your requests must be of type multipart/form-data
. If needed, you can use a FormData object for this.
Using Buffers
import { Context, Post } from '@foal/core';
import { ParseAndValidateFiles } from '@foal/storage';
export class UserController {
@Post('/profile')
@ParseAndValidateFiles({
profile: { required: true },
images: { required: false, multiple: true }
})
uploadProfilePhoto(ctx: Context) {
const { buffer } = ctx.files.get('profile')[0];
const files = ctx.files.get('images');
for (const file of files) {
// Do something with file.buffer
}
}
}
The names of the file fields must be provided as first parameter of the hook. Uploaded files which are not listed here are simply ignored.
For each file, you can provide the validation options below.
Validation option | Default value | Description |
---|---|---|
required | false | Specifies that at least one file must be uploaded for the given name. If not, the server returns a 400 - BAD REQUEST error. |
multiple | false | Specifies that multiple files can be uploaded for the given name. If set to false and multiple files are uploaded, the server returns a 400 - BAD REQUEST error. |