Search code examples
node.jsnestjsmulter

Manage uploaded image in nest js


I use multer to manage uploaded file:

@Post('upload') @UseInterceptors(FilesInterceptor("images", 10, {
  dest: "./uploads",
}))
uploadMultiple(@UploadedFiles() files) {
  console.log(files, 'test');
}

I try to add a file extension to my uploaded files as:

@Post('upload') @UseInterceptors(FilesInterceptor("images", 10, {
  dest: "./uploads",
   filename: function (req, file, cb) {
    cb(null, Date.now() + '.jpg') //Appending .jpg
  }
}))

But when I do this I get an error:

TS2345: Argument of type '{ dest: string; filename: (req: any, file: any, cb: any) => void; }' is not assignable to parameter of type 'MulterOptions'.   Object literal may only specify known properties, and 'filename' does not exist in type 'MulterOptions'

How to specify file extension to my uploaded files?


Solution

  • You can do it dynamically using the extname import from path using the diskStorage to get your filename extension.

    import { extname } from 'path';
    import { diskStorage } from 'multer';
    
    export const exampleDiskStorage = diskStorage({
      destination: './public/img/users',
      filename: (req, file, cb) => {
        return cb(null, `${Date.now()}${extname(file.originalname)}`);
      }
    });
    

    In your module, you only need to import the diskStorage to MulterModule.register

    import { MulterModule } from '@nestjs/platform-express';
    
    @Module({
      imports: [
        MulterModule.register({
          storage: exampleDiskStorage,
        }),
      ],
    });