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:

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay