multer-s3-transform文件上传不起作用

时间:2019-05-13 07:05:26

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

我正在使用multer-s3-transform将文件上传到s3,但是在上传之前我想调整文件大小,并保存为两种不同的大小。 以下是我的代码,没有错误发生,但是文件未上传。

let multer = require("multer-s3-transform");
const aws = require('aws-sdk');
const sharp = require('sharp');

aws.config.update({
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  accessKeyId: process.env.AWS_ACCESS_KEY_ID
);

const s3 = new aws.S3();
var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: process.env.AWS_BUCKET_NAME,
    shouldTransform: function (req, file, cb) {
      console.log("hereeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
      let originalname = file.originalname;
      file.stream.once('data', async function (firstChunk) {
        let magic = firstChunk.toString('hex', 0, 4);
        let extName = path.extname(originalname).toLowerCase();
        // let filename = req.file.fieldname + '-' + Date.now() + path.extname(req.file.originalname);
        if (checkMagicNumbers(magic, extName, req)) {
          console.log("Valid File***************************");
          cb(null, true);
        }
      });
    },
    transforms: [{
      id: 'original',
      key: async function (req, file, cb) {
        let basePath = await getDynamicFilePath(req, false);
        console.log(basePath, "Path ^^^^^^^^^^^^^^^^^^^^^^^");
        let filePath = basePath;
        let filename;
        if (req.params.container === "resumes") {
          void function (req, file, callback) {
            filename = Date.now().toString() + '-' + file.originalname;
            filePath += "/cropped_" + filename;
          }()
        } else {
          filename = Date.now().toString();
          filePath += "/cropped_" + filename;
        }
        console.log(filePath, "path -------------------");
        cb(null, filePath);
      },
      transform: function (req, file, cb) {
        cb(null, sharp().resize(330, 512))
      }
    }
    {
      id: 'thumbnail',
      key: async function (req, file, cb) {
        let basePath = await getDynamicFilePath(req, false);
        console.log(basePath, "Path ^^^^^^^^^^^^^^^^^^^^^^^");
        let filePath = basePath;
        let filename;
        if (req.params.container === "resumes") {
          void function (req, file, callback) {
            filename = Date.now().toString() + '-' + file.originalname;
            filePath += "/normal" + filename;
          }()
        } else {
          filename = Date.now().toString();
          filePath += "/normal_" + filename;
        }
        console.log(filePath, "path -------------------");
        cb(null, filename);
      },
      transform: function (req, file, cb) {
        cb(null, sharp().resize(1200, 628));
      }
    }
    ]
  })
}).single("file");
upload(req, res, function (err, filePath) {
  console.log(err, "Error");
  console.log(filePath, "*************");
});

如果我从multer-s3开始使用,一切工作正常,除了图像调整大小,但是使用multer-s3-transform时,不会发生任何错误,并且文件也没有上传,并且从不执​​行以下操作:

console.log(err, "Error"); console.log(filePath, "*************");

我已经找到了问题所在,在下面的代码块中,我想检查文件的幻数。

file.stream.once('data', async function (firstChunk) {
    let magic = firstChunk.toString('hex', 0, 4);
    let extName = path.extname(originalname).toLowerCase();
    // let filename = req.file.fieldname + '-' + Date.now() + path.extname(req.file.originalname);
    if (checkMagicNumbers(magic, extName, req)) {
      console.log("Valid File***************************");
      cb(null, true);
    }
  });

如果我对此发表评论,那么一切都会正常进行。 似乎在获取不可思议的文件数量时,文件更改为流,并且上传不起作用,将流更改回文件的方法可能有效。

2 个答案:

答案 0 :(得分:0)

为什么不通过将文件缓冲区转换为十六进制字符串而不是将文件转换为流并在 data 事件处理程序中访问它,然后将其转换为十六进制来计算和检查幻数?

shouldTransform: function(req, file, cb) {
      const originalname = file.originalname;
      const firstChunk = file.buffer;
      const magic = firstChunk.toString("hex", 0, 4);
      const extName = path.extname(originalname).toLowerCase();
      if (checkMagicNumbers(magic, extName, req)) {
        cb(null, true);
      }
    }

我希望这会有所帮助。如果您遇到任何困难,请告诉我。

答案 1 :(得分:0)

对我来说,更改以下内容有效。

let uploadToCloud = (req, res) => {
let bufferUpload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: 10485760
  }
}).single('file');
bufferUpload(req, res, async function (err) {
  try {
    let buffer = new Buffer(req.file.buffer);
    let magic = buffer.toString('hex', 0, 4);
    let extName = path.extname(req.file.originalname).toLowerCase();
    let filename;
    if (checkMagicNumbers(magic, extName, req)) {
       // Your codes
    }
  } catch (error) {
    res.status(400).json(error);
    res.end();
    return;
  }
 });
};