DEV Community

Agik Setiawan
Agik Setiawan

Posted on • Edited on

2 2

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:

Postmark Image

20% off for developers shipping features, not fixing email

Build your product without worrying about email infrastructure. Our reliable delivery, detailed analytics, and developer-friendly API let you focus on shipping features that matter.

Start free

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay