2016-11-08 516 views
4

我想Amazon S3的使用multer-s3來上傳圖片,但我得到這個錯誤:上傳圖像到Amazon S3使用multer-S3的NodeJS

TypeError: Expected opts.s3 to be object node_modules/multer-s3/index.js:69:20

這是我的服務器代碼:

var upload = multer({ 
    storage: s3({ 
     dirname: '/', 
     bucket: 'bucket', 
     secretAccessKey: 'key', 
     accessKeyId: 'key', 
     region: 'us-west-2', 
     filename: function (req, file, cb) { 
      cb(null, file.originalname); 
     } 
    }) 
}); 

app.post('/upload', upload.array('file'), function (req, res, next) { 
    res.send("Uploaded!"); 
}); 

爲什麼我得到這個錯誤?

回答

9

完成和工作Node Cheat | Upload to s3 using multer-s3可用。

代碼:

var express = require('express'), 
    aws = require('aws-sdk'), 
    bodyParser = require('body-parser'), 
    multer = require('multer'), 
    multerS3 = require('multer-s3'); 

aws.config.update({ 
    secretAccessKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', 
    accessKeyId: 'XXXXXXXXXXXXXXX', 
    region: 'us-east-1' 
}); 

var app = express(), 
    s3 = new aws.S3(); 

app.use(bodyParser.json()); 

var upload = multer({ 
    storage: multerS3({ 
     s3: s3, 
     bucket: 'bucket-name', 
     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 
app.get('/', function (req, res) { 
    res.sendFile(__dirname + '/index.html');//index.html is inside node-cheat 
}); 

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

app.listen(3000, function() { 
    console.log('Example app listening on port 3000!'); 
}); 

有關完整的回購

克隆節點騙express_multer_s3,運行之後npm install express body-parser aws-sdk multer multer-s3node app

快樂幫助!

+1

爲什麼沒有一百萬個這樣的答案喜歡?這幫助了我。謝謝。您可能想要更新:'aws.config.update({0} {0}} {0}}}}簽名版本:'v4',因爲我收到一個錯誤,並且這樣做解決了它。 – Somename

+1

真的很有幫助。 –

4

s3需要是要傳遞的對象。根據該文檔,對象需要是這樣的:

var upload = multer({ 
    storage: multerS3({ 
    s3: s3, 
    bucket: 'some-bucket', 
    metadata: function (req, file, cb) { 
     cb(null, {fieldName: file.fieldname}); 
    }, 
    key: function (req, file, cb) { 
     cb(null, Date.now().toString()) 
    } 
    }) 
}) 

MulterS3 Docs

+0

哪裏可以提供以上的accesskeyId – mBlaze

+0

@mBlaze:您需要使用aws sdk使用var s3 = new aws.S3({/ * ... * /})創建一個s3對象。你可以找到更多的信息使用鏈接http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-json-file.html – V31

+0

@mBlaze:只是想知道如果你能解決你的問題。如果是,那麼請標記接受的答案。 – V31

相關問題