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 many 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 extract the file. We also use the types package installed previously to type the file.

@UploadedFile() 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: Express.Multer.File) {
  return file;
}

Commit - Using multer to extract files

Last updated