node.js表达multer问题使用multer-s3 npm

时间:2017-01-08 12:30:32

标签: node.js express multer multer-s3

使用multer和multer-s3 npm以及node.js和express将图像上传到S3时出现问题。

我已阅读multer和multer-s3的文档,并按照教程,在stackoverflow和其他网站上搜索以解决我的问题,但没有成功。

这是我的客户端代码:

<form method="post" enctype="multipart/form-data" action="/test">
<p>
    <input type="text" name="title" placeholder="optional title"/>
</p>

<p>
    <input type="file" name="upl"/>
</p>

<p>
    <input type="submit"/>
</p>
</form>

这是我的服务器端代码: 的

var express = require('express'),
 router = express.Router(),
 aws = require('aws-sdk'),
 multer = require('multer'),
 multerS3 = require('multer-s3'),
 s3 = new aws.S3()

 aws.config = ({
  secretAccessKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  accessKeyId: 'XXXXXXXXXXXXXX'
});

var upload = multer({
   storage: multerS3({
       s3: s3,
       bucket: 'styleboxphotosbianor',
       key: function (req, file, cb) {
         console.log(file);
         cb(null, file.originalname); //use Date.now() for unique file keys
      }
  })
});

//open in browser to see upload form
router.get('/', function (req, res) {
   res.render('multer');
});

//use by upload form
router.post('/', upload.array('upl',1), function (req, res, next) {
  res.send("Uploaded!");
});

module.exports = router;

我收到了这个错误 的

TypeError: this.s3.upload is not a function
at S3Storage.<anonymous> (/Users/magintosh/bianor/node_modules/multer-s3/index.js:150:26)

所以我需要你帮助我的朋友。非常感谢你能来我们这里!

1 个答案:

答案 0 :(得分:3)

你必须创建&#34; s3&#34;只有在设置了你的&#34; aws&#34;模块。 并设置&#34; aws&#34;包应该是&#34; aws.config.update&#34;

var express = require('express'),
 router = express.Router(),
 aws = require('aws-sdk'),
 multer = require('multer'),
 multerS3 = require('multer-s3');

 aws.config.update({
  secretAccessKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  accessKeyId: 'XXXXXXXXXXXXXX'
});

 s3 = new aws.S3();

*我假设您替换&#34; secretAccessKey&#34;的值。和&#34; accessKeyId&#34;使用来自AWS的实际密钥,您确实拥有AWS账户(有些教程未提及)