Search code examples
javascriptnestjsmulter

How to prevent file saving if file already exists in multer


I am using multer with NetsJs, and storing the file like below

    @Post('upload')
    @UseInterceptors(FileInterceptor('file', {
        storage: diskStorage({
            destination: '\\nasmnt\\gtwac\\file_upload',
            filename: (req, file, callback) => {
                callback(null, file.originalname);
            },
        }),
    }),
    )
    uploadFile(@UploadedFile() file, @Query() dialer: DialerListType): void {
        console.log(JSON.stringify(dialer));
        console.log(file);

    }

When I upload same file again it will overwrite the old file, in my case I need to throw error if file already exists. How can I do that?

p.s I am new to multer


Solution

  • In case somebody else has same problem

    import { MulterModule } from '@nestjs/platform-express';
    import * as fs from 'fs';
    import { diskStorage } from 'multer';
    import * as path from 'path';
    ...
         MulterModule.registerAsync({
                imports: [SharedModule],
                useFactory: async (configService: ConfigService) => ({
                    storage: diskStorage({
                        destination: configService.config.dialerFilePath.upload,
                        filename: (req, file, callback) => {
                            callback(null, file.originalname);
                        },
                    }),
                    fileFilter: (req, file, callback) => {
    
                        if (fs.existsSync(path.join(configService.config.dialerFilePath.upload, file.originalname))) {
                            callback(new NotAcceptableException(`File ${file.originalname} is already uploaded!`));
                        } else {
                            callback(null, true);
                        }
                    },
                }),
                inject: [ConfigService],
            }),