使用Node将映像上传到AWS S3存储桶。 JS

时间:2018-10-13 16:17:57

标签: javascript node.js amazon-web-services amazon-s3 image-uploading

我正在尝试使用node.js将图像从网页上传到我的S3存储桶。我可以创建一个文件夹,但是将图像文件上传到该文件夹​​对我来说不起作用。这是我在package.json中的依赖项

"dependencies": {
    "aws-sdk": "^2.331.0",
    "bcrypt-nodejs": "0.0.3",
    "busboy": "^0.2.14",
    "busboy-body-parser": "^0.3.2",
    "connect-busboy": "0.0.2",
    "ejs": "^2.6.1",
    "express": "^4.16.3",
    "express-handlebars": "^3.0.0",
    "express-session": "^1.15.6",
    "mysql": "^2.16.0",
    "mysql2": "^1.6.1",
    "passport": "^0.4.0",
    "passport-local-sequelize": "^0.8.0",
    "path": "^0.12.7",
    "sequelize": "^4.39.0"
  }

这是我正在使用的api_routes.js文件的一部分

const bucketName = 'socialmemedia';
const bucketRegion = 'us-east-1';

AWS.config.update({
  region: bucketRegion
});
AWS.config.apiVersions = {
  s3: '2006-03-01',
};

const s3 = new AWS.S3();

module.exports = function (app) {
 // upload image to S3
  app.post("/api/upload", function (req, res) {
    const file = (req.body.imageUpload);
    const busboy = new Busboy({
      headers: req.headers
    });
    busboy.on('finish', function () {
      console.log('Upload finished');
      console.log(file);
      uploadToS3(file);
    });
     req.pipe(busboy);
  });


  function uploadToS3(file) {
    // console.log(req.body);

    const folder = (req.user.username + "/")
    console.log("Folder name: " + folder);
    const params = {
      Bucket: bucketName,
      Key: folder,
      ACL: 'public-read',
      Body: stream
    };

    s3.upload(params, function (err, data) {
      if (err) {
        console.log("Error: ", err);
      } else {
        console.log("Successfully created a folder on S3");
        
      }
    });
    res.redirect("/feed");
  }

};

这是表格片段

<form action="/api/upload" method="POST" class="image-form">
        <input id="image-upload" class="file-add" type="file" accept="image/*" name="imageUpload"/>
        <button type="submit" id="image-upload" class="sinsup-button">Upload Image</button>
</form>

关于如何使图像实际上传到S3存储桶的任何想法?

1 个答案:

答案 0 :(得分:3)

我知道了,谢谢您对我的帮助。我使用的是s3.upload而不是s3.putObject。回答以帮助将来可能会遇到此问题的其他任何人。

  // upload image to S3
  app.post("/api/upload", function (req, res) {
    const folder = (req.user.username + "/");
    const file = (req.body.imageUpload);
    const params = {
      Bucket: bucketName,
      Key: (folder + file),
      ACL: 'public-read',
      Body: file
    };
    console.log("Folder name: " + folder);
    console.log("File: " + file);
    

    s3.putObject(params, function (err, data) {
      if (err) {
        console.log("Error: ", err);
      } else {
        console.log(data);
      }
    });
    res.redirect("/feed");
  });