Nest js upload is not saving file

Viewed 3563

I'm following the nestjs documentation for File upload, my endpoint is getting the file, but the file is not stored.

I'm using the same configuration than NesJS

@Post('upload')
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file) {
  console.log(file);
}

My app.module file, I added the import for:

MulterModule.register({
      dest: './uploads'
    })

But the file is not stored in the directory uploads. The complete log is:

undefined
{
  fieldname: 'file',
  originalname: 'nopornimage.png',
  encoding: '7bit',
  mimetype: 'image/png',
  buffer: <Buffer 89 50 4e 47 0d 0a 1a 04 d00 01 73 52 47 42 00 ae ce 04 ... 20087 more bytes>,
  size: 20137
}

(Yes, including the undefined)

What am I doing wrong?

3 Answers

you should specify the destination. multer options

@Post('upload')
@UseInterceptors(FileInterceptor('file', {
  dest: 'uploads/'
}))
uploadFile(@UploadedFile() file) {
  console.log(file);
}

or you can use createWriteStream in fs module to save file by yourself.

import {createWriteStream} from 'fs'

@Post('upload')
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file) {
  const ws = createWriteStream('custom_filename')
  ws.write(file.buffer)
  console.log(file);
}

  1. you should register multer module in your domain module not in app module(unless app module is the only module in your project ) for example if your controller belongs to task domain you should register multer in task module not in app module
   imports: [
     TypeOrmModule.forFeature([TaskRepository]),
     MulterModule.register({ dest: './upload' }),
   ],
   controllers: [TaskController],
   providers: [TaskService],
 })
 export class TaskModule {}
  1. create upload directory and determine it's path in multer registration
@Post('upload')
@UseInterceptors(FileInterceptor('file', {dest: 'uploads/'}))
uploadFile(@UploadedFile() file: Express.Multer.File) {
    console.log(file);
}

You can use 'dest' keyword with decortor

Related