首页 > 解决方案 > nodejs 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);
        }
      });

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

标签: node.jsamazon-s3file-uploadmultermulter-s3

解决方案


你可以让你的代码更安全,里面有这条线。Aws-sdk 知道在哪里查找您的凭据。

消除:

Aws.config.credentials堵塞

添加:

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


推荐阅读