Basic file route

The first steps for managing files.

Let's go back to the ProductsController and add a new route, responsible for uploading an image of a product. The files section has some nuances, so let's proceed slowly so that we don't get lost in the process. We'll begin by creating a very simple route, and gradually add to its structure.

@Post(':id/image')
uploadImage() {
  return 'Uploaded an image';
}

We now have a route for this purpose. Let's then allow a file upload. To extract files in the route, the process is a bit similar to extracting path/query params. First, we should use the FileInterceptor, which has, as parameter, the name of the field that contains the file.

@UseInterceptors(FileInterceptor('file'))

Then pass, as argument to the route handler, the decorator @UploadedFile(), which will actually contain a reference to the file. We also use the types package installed previously to type the file.

@UploadedFile() file: Express.Multer.File

We may also create a type alias for this in src/files/types/file.types.

export type File = Express.Multer.File;

And we're done. We may even return the file to see its fields, obtaining the following result:

@UseInterceptors(FileInterceptor('file'))
@Post(':id/image)
uploadImage(@UploadedFile() file: File) {
  return file;
}

Commit - Using multer to extract files

Last updated