Since nestjs is an express app, it's possible to use any library to handle upload using nest, and since it provides Midlewares, it's also possible to use multer. My question is: What's the best way to handle file uploads using nestjs?
As informed by @Kamyl on issue https://github.com/nestjs/nest/issues/262, since v4.6.0
is possible to upload files using multer to nestjs using a common file interceptor.
import { ... , UseInterceptors, FileInterceptor, UploadedFile } from '@nestjs/common'
...
@UseInterceptors(FileInterceptor('file'))
async upload( @UploadedFile() file) {
console.log(file)
}
This way the variable file
will have a buffer
It's also needed the field name as the first param, then an array with Multer Options
import { ... , UseInterceptors, FileInterceptor, UploadedFile } from '@nestjs/common'
import { diskStorage } from 'multer'
import { extname } from 'path'
...
@UseInterceptors(FileInterceptor('file', {
storage: diskStorage({
destination: './uploads'
, filename: (req, file, cb) => {
// Generating a 32 random chars long string
const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('')
//Calling the callback passing the random name generated with the original extension name
cb(null, `${randomName}${extname(file.originalname)}`)
}
})
}))
async upload( @UploadedFile() file) {
console.log(file)
}
This way the variable file
will have a filename
, destination
and path
.
The destination
param from the diskStorage
can also be a function, with the parameters and expecting the callback the same as filename
. By passing a diskStorage
the file will be automatically saved to the destination informed with the filename given.
It's also possible to handle multiple files by using @UploadedFiles
and FilesInterceptor
(plural)