在上传到s3 nodejs之前处理并上传多个文件

时间:2019-01-15 17:16:11

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

大家好,所以我有一点问题。我有以下代码,如果我想上传单个文件,效果很好。看起来像这样:

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

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 fieldName = "image";
var newFileName = "myCustomFileName1";
singleFileUpload(req, res, newFileName, process.env.BUCKET_NAME, fieldName);

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

我得到MulterError:意外字段。实际上,如果我在文件数组中还有另一个文件,即使我没有两次调用该函数,也会出现此错误。我希望能够为每个字段自定义fileName。不使用单个<input type="upload" name="myfiles" multiple>,而是使用表单中每个文件的上载字段。 在前端。这里的任何帮助都会很棒!谢谢

0 个答案:

没有答案