【发布时间】:2019-04-06 21:29:10
【问题描述】:
我正在尝试将图像上传到 s3 存储桶作为应用程序的一部分。
index.js
function upImg(req) {
if(req.files.img) {
var img = req.files.image;
var name = Math.round(Math.random()*10000).toString(); // Returns a random 5 digit number
if(myDB.uploadImg(img, name)) {
return name;
} else {
return "";
}
} else {
return "";
}
}
app.post('/newEV*', isLoggedIn, function(req, res) {
var myURL = req.path.replace('/newEV', '');
var imgPath = upImg(req);
fetch(myURL).then(function (events){
var myID;
var x = 0;
while(!myID) {
if(!events[x]) {
myID = x;
} else {
x++;
}
}
myDB.newEvent(myURL, req.body.name, req.body.desc, req.body.loc, imgPath, req.body.link, req.body.cap, req.body.date, req.body.time, myID, events);
res.redirect('/edit' + myURL);
});
});
myDB 文件
function signs3(file, name) {
devs3();
const s3 = new aws.S3();
const s3Params = {
Body: file,
Bucket: S3_BUCKET,
Key: name
};
s3.putObject(s3Params, function(err, data) {
if(err) {
throw err;
} else {
console.log("Data from putObject:" + JSON.stringify(data));
}
});
}
module.exports = {
uploadImg : function(file, name) {
var nName = "imgs/" + name;
console.log(nName);
signs3(file, nName);
return true;
}
}
我知道signs3 函数有效,因为我可以在我的应用程序的其他部分中使用它来上传JSON 文件。每当我发布到 URL 时,奇怪的是我可以在控制台中看到“来自 putObject 的数据”,但是我看不到的是 nName。我不明白这一点,因为console.log(nName) 行应该在另一行之前运行。当我去查看存储桶时,图像尚未上传(尽管我从控制台获取了 ETag),并且页面没有显示在那里(我知道这也有效,因为它可以显示已经上传到存储桶的图像)。
【问题讨论】:
-
上传是异步的
-
我知道,我在上传 JSON 文件时使用了与此类似的方法,它可以工作。
标签: javascript node.js express amazon-s3 aws-sdk