DEV Community

Agik Setiawan
Agik Setiawan

Posted on • Edited on

Upload file to Object Storage (S3) in Nest JS

This is how to upload file to object storage like AWS S3, Minio, and another similarly in NestJS Framework.

I use package nestjs-multer-extended

Install package with yarn or npm

yarn add nestjs-multer-extended
Enter fullscreen mode Exit fullscreen mode

In your module

import { MulterExtendedModule } from 'nestjs-multer-extended';
Enter fullscreen mode Exit fullscreen mode
@Module({
    imports: [
        MulterExtendedModule.register({
    awsConfig: {
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
        region: process.env.AWS_DEFAULT_REGION,
    },
    bucket: process.env.AWS_BUCKET,
    basePath: 'public',
    fileSize: 1 * 1024 * 1024,
    endpoint: process.env.AWS_ENDPOINT,
});
    ],
})
Enter fullscreen mode Exit fullscreen mode

In your controller

@UseInterceptors(AmazonS3FileInterceptor('path', { dynamicPath: 'folder_name_or_root', randomFilename: true }))
  @Post()
  async create(@UploadedFile() file, @Body() createProductGalleryDto: CreateProductGalleryDto) {
    if (file) {
      createProductGalleryDto.path = file.key;
    }
    return await this.productGalleryService.create(createProductGalleryDto);
  }
Enter fullscreen mode Exit fullscreen mode

You can save file path into database with name "file.key:

Top comments (0)