change need
change need

Reputation: 157

upload image to s3 from node js

I'm trying to upload a file to s3 but it not happening what I expected. I create a file-helper.js in middleware, that is looks like below

const aws = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3');

aws.config.update({
        accessKeyID:'XXXXXXXXXXXXXX',    
        SecretAccessKey:'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
        region:'ap-south-1'
});

const s3 = new aws.S3();

const fileFilter = (req, file, cb) => {
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
      cb(null, true);
    } else {
      cb(new Error('Invalid file type, only JPEG and PNG is allowed!'), false);
    }
  }

const upload = multer({
    fileFilter,
    storage: multerS3({
      s3,
      bucket: 'demo.moveies.com',
      acl: 'public-read',
      metadata: function (req, file, cb) {
        cb(null, {fieldName: file.fieldname});
      },
      key: function (req, file, cb) {
        cb(null, Date.now().toString())
      }
    })
  })

  module.exports = upload;

and my controller file like below

const upload = require('../middleware/file-helper');
const imageUpload = upload.single('image');
exports.fileUpload = async(req,res)=>{
    imageUpload(req, res, function(err, some) {
        if (err) {
          return res.status(422).send({errors: [{title: 'Image Upload Error', detail: err.message}] });
        }
        return res.json({'imageUrl': req.file.location});
      });
}

when hit the API end point it is giving error

{ "errors": [ { "title": "Image Upload Error", "detail": "Missing credentials in config" } ] }

I'm not able to figure out where I went in wrong in my code. can one help me in this situation

Upvotes: 1

Views: 933

Answers (2)

Chukwualuka Chiama
Chukwualuka Chiama

Reputation: 338

There are typos in your config details. It should be accessKeyId not accessKeyID and secretAccessKey and not SecretAccessKey.

Upvotes: 1

hashed_name
hashed_name

Reputation: 551

You have used the wrong key SecretAccessKey and accessKeyID, try changing it to secretAccessKey and accessKeyId.

aws.config.update({
    accessKeyId:'XXXXXXXXXXXXXX',    
    secretAccessKey:'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
    region:'ap-south-1'
});

Upvotes: 1

Related Questions