Image Upload to AWS S3 using Nestjs and TypeScript.

Shamnad Shaji
2 min readJul 21, 2018

--

Recently I had to do an image upload to AWS S3 in my project using Nestjs and Typescript in the backend. I am sharing the simple steps to do this using Typescript and Nestjs, even though this code is for Nestjs and typescript you can refer this for image upload for Nodejs with express too and make the changes accordingly.

First thing you would need to setup an AWS S3 bucket for image upload. You can refer my medium story on that if you dont know how to do it.

Now you need to setup your backend code for image upload using typescript. You would need the below dependencies for setting up the image upload to S3.

npm install aws-sdk multer multer-s3 --save

Now all your required dependencies are in place and we can setup the constructor route for image upload

Now you need to have a service class for the same.

You need to replace the environment variables with the proper values.

AWS_S3_BUCKET_NAME
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY

Describing the service class

Service class is handling the image upload and as you can see there is an upload method, with uploads the file using multer and multer-s3 . The field to send the file is named as upload . and the number of files is specified as the next param. Since we only have one file we are giving the value as 1. array('upload',1). You need to use the same name while making the upload requet to the controller.

And the uploaded file url can be retrieved as req.files[0].location. Since in this case we only have one file, index 0 would do.

Now you need to create the module file for the same.

Now you need to connect this Module to the App Module imports.

Now you can run your typescript application using npm start. Once the application is up and running you can test your image upload using postman.

Testing Using postman

Make sure to select form-data and enter key as upload and then select a file and send the request to server. If you have given the AWS credentials and bucket name correctly then the image will be uploaded to S3 and you will get the image url as response.

Thank you for reading!.

The entire source code for this can be found here.

Let me know if you have any feedback or comments or if you face any issues.

--

--

Shamnad Shaji

I am a programmer who loves new challenges and here to make everyday development easy for developers by sharing my experiences.