In this tutorial, you will learn how to upload a file to an amazon s3 bucket using node js express with aws-s3, multer package.
How to Upload Files to Amazon s3 bucket using Node JS + Express?
Steps to upload single or multiple files to aws s3 bucket:
Step 1 – Create Node Express js App
Run the following command on cmd to create node js app:
mkdir my-app
cd my-app
npm init -y
Step 2 – Install express, aws-s3, Multer dependencies
Run the following command on cmd to install express, aws-s3 and multer dependencies:
npm install express multer aws-sdk body-parser --save
Step 3 – Create Server.js File
Create server.js
file in your application root directory, and follow the below steps:
- Import Installed Packages
- Configure AWS-S3 Package with Multer
- Create Uploading Single File to AWS S3 with Node.js REST API Route
- Create Uploading Single File to AWS S3 with Node.js REST API Route
Import Installed Packages
Import above installed dependencies package in server.js file:
var aws = require('aws-sdk') var express = require('express') var multer = require('multer') var multerS3 = require('multer-s3')
Configure AWS-S3 Package with Multer
Then configure aws-s3 package with multer as shown below:
var s3 = new aws.S3({ accessKeyId: " ", secretAccessKey: " ", Bucket: " " }) var upload = multer({ storage: multerS3({ s3: s3, bucket:””, metadata: function (req, file, cb) { cb(null, { fieldName: file.fieldname }); }, key: function (req, file, cb) { cb(null, Date.now().toString()) } }) })
Create Uploading Single File to AWS S3 with Node.js REST API Route
The following node js rest api route will be upload single file to amazon s3 bucket:
//Uploading single File to aws s3 bucket app.post('/upload', upload.single('photos'), function (req, res, next) { res.send({ data: req.files, msg: 'Successfully uploaded ' + req.files + ' files!' }) })
Create Uploading Multiple File to AWS S3 with Node.js REST API Route
The following node js rest api route will be upload multiple file to amazon s3 bucket:
//Uploading single File to aws s3 bucket app.post('/upload', upload.single('photos'), function (req, res, next) { res.send({ data: req.files, msg: 'Successfully uploaded ' + req.files + ' files!' }) })
Step 4 – Start Node Express Js Application
Run the following command on cmd to start node express js server:
//run the below command npm start
Step 5 – Uploading Files to AWS S3 Bucket with Node.js REST API
To upload single or multiple files to aws s3 bucket using node js rest API; So open postman for sending HTTP multipart/form-data
requests: as shown below picture:
Conclusion
That’s it, you have learned how to upload files to the amazon s3 bucket using node js + rest api+ express with the express, aws-s3, multer package.