AWS使用Node.js将照片上传到s3存储桶

时间:2018-03-21 00:30:08

标签: amazon-web-services amazon-s3 aws-sdk aws-cli

我无法将照片上传到我的s3水桶。我认为这是凭据错误。我可以使用aws cli上传照片,但无法上传使用此node.js代码(我得到超时):

var config = require('./config.json');
var AWS = require('aws-sdk');
AWS.config.update({region:config.awsRegion});
var s3 = new AWS.S3();
var fs = require('fs');



 module.exports.upload = function(fileName, cb){
   var bitmap = fs.readFileSync('./photos/'+fileName);

   var params = {
     Body: bitmap,
     Bucket: config.s3Bucket,
     Key: fileName
    };
    s3.putObject(params, function(err, data) {
      fs.exists('./photos/'+fileName, function(exists) {
        if(exists) {

          fs.unlink('./photos/'+fileName);
        }
        });

      if (err) {
        console.log(err, err.stack);
        cb(err);
      }else{
        //console.log(data);
        cb(null,data);           // successful response
      }

    });
}

有人有任何线索吗?

这是主要的服务器代码:

const express    = require('express');        // call express
const app        = express();                 // define our app using express
const bodyParser = require('body-parser');
const basicAuth = require('express-basic-auth');
const Raspistill = require('node-raspistill').Raspistill;
const camera = new Raspistill({
    width: 600,
    height: 600,
    time:1
});


const s3upload = require('./upload-s3');
const speaker = require('./speaker');
const faceSearch = require('./search-faces');


app.use(basicAuth({
    users: { 'raspi': 'secret' }
}))

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 80;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});
router.post('/capture', function(req, res) {
  var fileName = new Date().getTime()+".jpg";
  console.log('filename', fileName);
  camera.takePhoto(fileName).then((photo) => {
    console.log('photo captured');
    //speaker.speak('Image has been captured... ');
    s3upload.upload(fileName, function(err,data){
        if(err){
          res.json({ status: 'fail' });
        }else{
          console.log('uploaded image to s3 bucket: '+fileName);
          //speaker.speak('Image has been uploaded to S3 bucket raspi118528');
          faceSearch.search(fileName, function(err, data){


            if(!err){

              if(data.FaceMatches && data.FaceMatches.length>0){

                  //var text = 'Hello '+data.FaceMatches[0].Face.ExternalImageId + '. How are you?';
                  var text = data.FaceMatches[0].Face.ExternalImageId ;
                  // text += Number.parseFloat(data.FaceMatches[0].Similarity).toFixed(2)+' % confident that you are '+
                  // data.FaceMatches[0].Face.ExternalImageId;
                  //speaker.speak(text);
                  res.json({ status: 'matched', key: fileName ,message: text});

              }else{
                  res.json({ status: 'unmatched', key: fileName ,message: "Hello! We never met before. What's your name?"});
                  //speaker.speak("Hello! We never met before. What's your name?");
              }
            }else{

              //speaker.speak("I can's see any faces. Are you human?");
                res.json({ status: 'error', key: fileName ,message: "I can's see any face. Please come in front of camera?"});
            }
          })

        }
    })
  });

});
// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

再次,我可以使用aws s3 cp上传照片cat.jpg s3:// raspberrypijohnypie / --region us-east-1

但我的凭据肯定有问题。这是因为在我的服务器拍摄照片并将其存储在照片文件夹中后,它无法上传。

2 个答案:

答案 0 :(得分:0)

您的代码似乎没问题,但您没有明确传递任何凭据。如果您在EC2实例或附加角色的Lambda函数中运行它,或者如果您在本地运行代码但具有包含您的凭据集的环境变量,则可以。没有它们不会导致超时,相反putObject函数将返回403错误。

我建议您注释掉检查和删除文件的部分,看看执行是否至少达到这一点,如果是,那么它会抛出什么错误(一旦文件没有在你的桶中结束我假设发生了错误。)

如果您想尝试使用显式传递凭据进行测试,那么您应该像这样实例化您的S3客户端

var s3 = new AWS.S3({
    apiVersion: '2006-03-01',
    accessKeyId: '',
    secretAccessKey: ''
});

另一个(无关)点,在检查错误之前删除您的照片是危险的。如果发生任何错误,您将永远丢失它。您应该在错误检查后移动删除逻辑。

答案 1 :(得分:0)

好像你需要传递凭证。允许代码从aws凭证文件中读取凭据总是更好。所以步骤是:
 1.在主目录中创建.aws文件夹  2.在内部导航并使用名称'
创建一个文件  3.加入“默认”'在顶部,然后将您的区域和两个访问键添加到另一个下面的行上  4.在您的代码中,请按以下方式阅读:

const credentials = new AWS.SharedIniFileCredentials({profile: 'default'});  
AWS.config.credentials = credentials;  

在上面的行之后,您可以初始化S3对象并尝试进行CRUD操作。

P.S。:既然你可以使用aws-cli,你应该已经设置了.aws文件夹了!