可重用的nodejs s3存储桶上传脚本

时间:2019-01-14 19:19:20

标签: node.js amazon-s3 file-upload multer multer-s3

嘿,我正在尝试将文件上传到s3,我可以使用以下代码成功完成此操作。但是,我想使其更具可重用性。我希望能够使用这样的功能。

singleFileUpload(fieldName, bucketName, newfileName);

这样我就可以在多个页面上使用相同的功能,而不必一遍又一遍地定义它。我也希望它能够在try catch块中返回任何上传错误。这可能吗?这是到目前为止我可以使用的代码。

var AWS = require("aws-sdk");
var multer = require("multer");
multerS3 = require("multer-s3");
var fs = require("fs");
AWS.config.credentials = {
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  region: "eu-west-1"
};
AWS.config.region = "eu-west-1";
var s3 = new AWS.S3();

var newFileName = "coolNewFileName";
      const fileFilter = (req, file, cb) => {
        var ext = file.originalname.split(".")[1];
        console.log("ext", ext);
        if (ext == "jpg" || ext == "mp4" || ext == "wmv") {
          cb(null, true);
        } else {
          cb(new Error("invalid file format"), false);
        }
      };

      var upload = multer({
        fileFilter,
        storage: multerS3({
          s3,
          bucket: process.env.BUCKET_NAME,
          acl: "public-read",
          metadata: function(req, file, cb) {
            cb(null, { fieldName: "testing_meta_data!" });
          },
          key: function(req, file, cb) {
            console.log(file);
            let fileExtension = file.originalname.split(".")[1];
            cb(null, newFileName + "." + fileExtension);
          }
        })
      });
      var singleUpload = upload.single("image");
      singleUpload(req, res, function(err) {
        if (err) {
          data.error = true;
          data.message = err.message;
          console.log(data);
          res.json(data);
        } else {
          // res.json({ imageurl: req.file.location });
          data.fileUploadLocation = req.file.location;
          console.log(data.fileUploadLocation);
        }
      });

在这里的任何帮助都非常感谢。

2 个答案:

答案 0 :(得分:0)

这是将以下代码放置在单独文件中的方式。 aws文件包含aws的include和s3配置。像这样:

    var AWS = require("aws-sdk");
    AWS.config.credentials = {
      accessKeyId: process.env.AWS_ACCESS_KEY_ID,
      secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
      region: "eu-west-1"
    };
    AWS.config.region = "eu-west-1";

    var s3 = new AWS.S3();

    module.exports = { AWS, s3 };

var AWS = require("../AWS").AWS;
var s3 = require("../AWS").s3;
var multer = require("multer");
var multerS3 = require("multer-s3");

比我包括以下代码如下:

let singleFileUpload = require(“ ../ upload”);

最后,我像这样在upload / index.js文件中构建函数:

function singleFileUpload(req, res, newFileName, bucketName, fieldName) {
  var fileFilter = (req, file, cb) => {
    var ext = file.originalname.split(".").slice(-1);
    console.log("ext", ext);
    if (ext == "jpg" || ext == "mp4" || ext == "wmv") {
      cb(null, true);
    } else {
      cb(new Error("invalid file format"), false);
    }
  };
  var upload = multer({
    fileFilter,
    storage: multerS3({
      s3,
      bucket: bucketName,
      acl: "public-read",
      metadata: function(req, file, cb) {
        cb(null, { test: "testing_meta_data!" });
      },
      key: function(req, file, cb) {
        console.log(file);
        let fileExtension = file.originalname.split(".")[1];
        cb(null, newFileName + "." + fileExtension);
      }
    })
  });
  var singleUpload = upload.single(fieldName);
  singleUpload(req, res, error => {
    if (error) {
      throw error;
    } else {
      console.log("it worked");
    }
  });
}

module.exports = singleFileUpload;

我不像这样运行函数:

 var newFileName = "Testing";
  var fieldName = "image";
  singleFileUpload(
    req,
    res,
    newFileName,
    process.env.BUCKET_NAME,
    fieldName
  );

答案 1 :(得分:0)

使用此行可以使您的代码更安全。 Aws-sdk知道在哪里可以找到您的凭据。

删除:

Aws.config.credentials

添加:

const credentials = new AWS.SharedIniFileCredentials({profile: 'name-of-profile'});