1
require("dotenv").config();
const AWS = require("aws-sdk");
const multer = require("multer");
const multerS3 = require("multer-s3");
const uuid = require("uuid").v4;
const path = require("path");

const s3 = new AWS.S3({
  accessKeyId: process.env.AWS_S3_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_S3_SECRET_ACCESS_KEY
});

const upload = multer({
  storage: multerS3({
    s3: s3,
    Bucket: process.env.AWS_S3_BUCKET_NAME,
    ACL: "public-read",
    metadata: (req, file, cd) => {
      cd(null, { fieldName: file.fieldname });
    },
    key: (req, file, cb) => {
      const ext = path.extname(file.originalname);
      const uniqueName = `${uuid()}${ext}`;
      cb(null, uniqueName);
    },
  }),
});

module.exports = {
    upload
} 
router.post("/photo-upload", upload.array('photos'), (req, res) => {  
    return res.status(200).send({
      success: true,
      result: 'Images Uploaded',
    });
  });

After adding this code my code is crashing and getting below errors **node_modules/multer-s3/index.js:94 case 'undefined': throw new Error('bucket is required')

Error: bucket is required at new S3Storage**

is there any way to upload multiple file at a time not using loop. Body: buffer, can I send it as a [buffer, buffer]?

Arun M
  • 133
  • 1
  • 11

1 Answers1

1

I would suggest you maybe consider using multer and multerS3 libraries, this would look as follows.

fileUpload.js

    const aws = require("aws-sdk")
    const multer = require("multer")
    const multerS3 = require("multer-s3")
    const uuid = require("uuid").v4
    const path = require("path")

    const s3 = new aws.S3({
        accessKeyId: <secret-id>,
        secretAccessKey: <secret-key>,
        region: <server-region>,
        apiVersion: "2012-10-17"
    })
    
    const upload = multer({
        storage: multerS3({
            s3:s3,
            bucket: <bucket-name>,
            acl: "public-read",
            metadata: (req, file, cd) => {
                cd(null, {fieldName: file.fieldname})
            },
            key: async (req, file, cb) => {
                const ext = path.extname(file.originalname)
                const uniqueName = `${uuid()}${ext}`
                cb(null, uniqueName)
            },
            
            
        })
    })

You then import the file into your routes and add upload.array to the route you want to upload images on

imageRoutes.js

const express = require("express");
const router = express.Router();
const upload = require("./fileUpload")
    
    router.post("/", upload.array("image"), (req, res) => {
    res.send("uploaded")
    }

    module.exports = router;
Arun M
  • 133
  • 1
  • 11
Erykj97
  • 158
  • 10
  • I'm getting below error node_modules/multer-s3/index.js:94 case 'undefined': throw new Error('bucket is required') – Arun M Jan 24 '21 at 05:33
  • did you run the following commands in your terminal to install both multer and multers3 npm install multer multer-s3 – Erykj97 Jan 24 '21 at 09:48
  • yes package.json "dependencies": { "aws-sdk": "^2.828.0", "bcrypt": "^5.0.0", "body-parser": "^1.19.0", "dotenv": "^8.2.0", "express": "^4.17.1", "joi": "^17.3.0", "joi-objectid": "^3.0.1", "jsonwebtoken": "^8.5.1", "mongoose": "^5.11.8", "multer": "^1.4.2", "multer-s3": "^2.9.0", "nodemailer": "^6.4.17", "twilio": "^3.54.1", "underscore": "^1.12.0", "uuidv4": "^6.2.6" } – Arun M Jan 24 '21 at 09:50
  • Could you update the post with your current code like the multer and routes – Erykj97 Jan 24 '21 at 09:53
  • This thread might be of help https://stackoverflow.com/questions/40494050/uploading-image-to-amazon-s3-using-multer-s3-nodejs – Erykj97 Jan 24 '21 at 10:08
  • I found the issue, This line Bucket: process.env.AWS_S3_BUCKET_NAME causing issue. env not working inside s3 object. I changed to const Bucket = process.env.AWS_S3_BUCKET_NAME and inside s3 storage: multerS3({ s3: s3, bucket: BucketName, acl: "public-read", metadata: (req, file, cd) => { cd(null, { fieldName: file.fieldname }); }, key: (req, file, cb) => { const ext = path.extname(file.originalname); const uniqueName = `${uuid()}${ext}`; cb(null, uniqueName); }, }) – Arun M Jan 24 '21 at 10:28
  • Erykj97, Thanks a lot for the help – Arun M Jan 24 '21 at 10:29
  • No Problem, if you found my post useful press the up arrow maybe it will help someone else in the future :) – Erykj97 Jan 24 '21 at 10:42