从节点js上传图像到s3

时间:2019-05-18 07:48:26

标签: node.js amazon-s3

我正在尝试将文件上传到s3,但未达到我的预期。 我在中间件中创建了一个file-helper.js,如下图所示

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;

和我的控制器文件如下

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});
      });
}

当到达API端点时,它给出了错误

  

{      “错误”:[         {              “ title”:“图像上传错误”,              “ detail”:“配置中缺少凭据”          }      ]   }

我无法弄清楚代码中哪里出了错。在这种情况下可以帮助我吗

2 个答案:

答案 0 :(得分:1)

您的配置详细信息中有错别字。应该是accessKeyId,而不是accessKeyIDsecretAccessKey,而不是SecretAccessKey

答案 1 :(得分:1)

您使用了错误的密钥SecretAccessKeyaccessKeyID,请尝试将其更改为secretAccessKeyaccessKeyId

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