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



我在将照片上传到 s3 存储桶时遇到问题。我认为这是一个凭据错误。我可以使用 aws cli 上传照片,但不能使用此节点上传.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://覆盆子皮约翰尼派/--region us-east-1

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

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

我建议您注释掉检查和删除文件的部分,看看执行是否至少达到该点,如果是,它抛出什么错误(一旦文件没有最终进入您的存储桶,我假设错误正在发生)。

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

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

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

似乎您需要传递凭据。最好允许代码从 aws 凭证文件中读取凭证。因此,步骤将是:
1.在您的主目录中创建.aws文件夹。
2. 在内部导航并创建一个名为"凭据"的文件
3.在顶部输入"[默认]",然后在一行下方添加您的区域和两个访问键。
4. 在您的代码中,像这样阅读:

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

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

PS:由于您可以使用 aws-cli,因此您应该已经设置了 .aws 文件夹!

相关内容

最新更新