首页 > 解决方案 > 无法成功上传图片到s3然后查看

问题描述

我正在尝试将图像作为应用程序的一部分上传到 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);
  });

});

我的数据库文件

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),并且页面没有显示在那里(我知道这也有效,因为它可以显示已经上传到存储桶的图像)。

标签: javascriptnode.jsexpressamazon-s3aws-sdk

解决方案


您想做这样的事情,从调用putObject时创建的Request 对象请求事件。

const req = s3.putObject( s3Params )
req.on('success', res => {
  console.log ('upload complete! );
});
req.on ('error', res => {
  console.error (res.error');
});
req.send();

为什么这对于小文件(JSON 文件)和大文件(图像)的工作方式似乎不同?因为大文件需要更长的时间来上传。


推荐阅读