How to read the upload file path from env on NestJS?

I’m working on NestJS. I’m making the API to upload a file but I’m facing the issue I can’t read the path outside the function. Below is my example code,

  @Post('product/image/:brandNo')
  @UseInterceptors(
    FilesInterceptor('files', 2, {
      storage: diskStorage({
        destination: (req, file, cb) => {
          const brandNo = req.params.brandNo;
          const directory = `../PRODUCT_BBA/${brandNo}/images`;
          if (!fs.existsSync(directory)) {
            fs.mkdirSync(directory, { recursive: true });
          }
          cb(null, directory);
        },
        filename: function (req, file, callback) {
          callback(null, file.originalname);
        },
      }),
    }),
  )
  @ApiBody({
    required: true,
    type: 'multipart/form-data',
    schema: {
      type: 'object',
      properties: {
        files: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @ApiBearerAuth()
  @ApiConsumes('multipart/form-data')
  async uploadProductImage(
    @Headers('Authorization') auth,
    @Param('brandNo') brandNo,
    @Res() res: Response,
    @UploadedFiles(
      new ParseFilePipeBuilder()
        .addFileTypeValidator({
          fileType: /(jpg|jpeg|png|gif)$/,
        })
        .addMaxSizeValidator({ maxSize: 20242880 })
        .build({
          errorHttpStatusCode: HttpStatus.UNPROCESSABLE_ENTITY,
        }),
    )
    files: Array<Express.Multer.File>,
  ) {
     //....todo
  }

According to the code, I wanna make the PRODUCT_BBA is readable from the .env file be cause this path need to be changed regarding to environment. How can I do this ?

Normally I do like,

  let basePath="";
  constructor(
    configService: ConfigService,
  ) {
     this.basePath = configService.get('BASE_PATH');
  }

But I cannot inject the basePath variable inside the destination scope

Thanks for every help and contribution.

Leave a Comment