Please wait...

File upload AWS S3 using NodeJs in rest-full api

@image  @ file  @ AWS  @ S3  @ NodeJS   @ Rest-Full  @ API  @ Multer-S3  @ Express  @ Multer  @ Base64  @ Delete  @ Post  

Create AWS S3 file upload using nodejs, multer-s3 npm package.


The official AWS SDK for JavaScript, available for browsers and mobile devices, or Node.js backends

For release notes, see the CHANGELOG. Prior to v2.4.8, release notes can be found at

If you are upgrading from 1.x to 2.0 of the SDK, please see the [upgrading]( notes for information on how to migrate existing code to work with the new major version.

link :


Streaming multer storage engine for AWS S3.

This project is mostly an integration piece for existing code samples from Multer's storage engine documentation with s3fs as the substitution piece for file system. Existing solutions I found required buffering the multipart uploads into the actual filesystem which is difficult to scale.

Link :

Create a new Directory, we can run the following command: 

mkdir <directoryname>

then move into the newly created directory:

cd <directoryname>

then  run this command : 

npm init

and fill this information like that :

package name: (directoryname)
version: (1.0.0)
entry point: (index.js) server.js
test command:
git repository:
license: (ISC)
{"name": "curlapi",  "version": "1.0.0","description": "", "main": "server.js","scripts": { "test": "echo \"Error: no test specified\" && exit 1" },  "author": "",  "license": "ISC"}Is this ok? (yes) yes then enter

After creating project install node package run command:

npm install --save express morgan body-parser method-override multer aws-sdk multer-s3

create the server.js file and add this code :

var express  = require('express');
var app      = express();                               // create our app w/ express
var morgan = require('morgan');             // log requests to the console (express4)
var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
var methodOverride = require('method-override');
var multer  =   require('multer');
var multerS3 = require('multer-s3')
// import entire SDK
var AWS = require('aws-sdk');
    accessKeyId: "<AWS ACCESSKEYID>",
    secretAccessKey: "AWS SECRETACCESSKEY",
    "region": "us-east-1"  
var s3 = new AWS.S3({ params: {Bucket: '<S3 Bucket Name>'} });
var bucketName = 'S3 Bucket Name';

app.use(function(req, res, next) { //allow cross origin requests
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
    res.header("Access-Control-Max-Age", "3600");
    res.header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// configuration
app.use(express.static(__dirname + '/public'));                 // set the static files location /public/img will be /img for users
app.use('/public/uploads',express.static(__dirname + '/public/uploads'));
app.use(bodyParser.json({limit: '50mb'}));                          // log every request to the console
app.use(bodyParser.urlencoded({limit: '50mb','extended':'true'}));            // parse application/x-www-form-urlencoded                                // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json

// file upload code
var storage1 = multer.diskStorage({ //multers disk storage settings
    destination: function (req, file, cb) {
        cb(null, '<S3 Bucket Name>/')
    filename: function (req, file, cb) {
        var datetimestamp =;
        cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])

var uploadSingle = multer({ //multer settings
        // storage: storage1
        storage: multerS3({
            s3: s3,
            bucket: '<S3 Bucket Name>',
            acl: 'public-read',
            key: function (req, file, cb) {
               var datetimestamp =;
               cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])

// Upload base64 image in s3'/api/getBase64ImgPath', function(req, res) {
    var name = 'file-' + Math.floor(10000000000 + Math.random() * 90000000000)+".jpg";
    buf = new Buffer(req.body.base64ImageData.replace(/^data:image\/\w+;base64,/, ""),'base64');
      var data = {
        ACL: 'public-read',
        Key: name, 
        Body: buf,
        ContentEncoding: 'base64',
        ContentType: 'image/jpeg'
      s3.putObject(data, function(err, data){
          if (err) { 
            console.log('Error uploading data: ', data); 
          } else {
            res.json({path:"<S3 Bucket Name>/"+name});

// delete image in s3 

// delete product
app.delete('/api/removeProduct', function(req, res) {
   var delete_images = req.body.images;
   var params = {
      Delete: { // required
        Objects: [],
    delete_images.forEach(function(file_path) {
        var file  = file_path.split('/');
        file = file[file.length-1]
        // fs.unlink(file_path);
    s3.deleteObjects(params, function (err, data) {
        if (data) {
            console.log("File deleted successfully",data);
        else {
            console.log("Check if you have sufficient permissions : "+err);

app.listen(process.env.PORT || 9000, function(){console.log("App listening on port 9000");});


Github Link:

Comments 0