【问题标题】:multer-s3-transform file upload is not workingmulter-s3-transform 文件上传不起作用
【发布时间】:2019-09-30 02:43:39
【问题描述】:

我正在使用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);
    }
  });

如果我对此发表评论,则一切正常。 似乎在获取文件的幻数时,将文件更改为流,并且上传不起作用,将流更改回文件的方法可能会起作用。

【问题讨论】:

  • 你是怎么解决的?请分享你的答案,我也需要这样做

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


【解决方案1】:

为什么不通过将文件缓冲区转换为十六进制字符串来计算和检查幻数,而不是将文件转换为流并在 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);
      }
    }

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

【讨论】:

  • 谢谢,但这行const firstChunk = file.buffer;返回未定义
  • 你能帮我检查两件事吗,看看file 的值是多少,然后试试req.file.buffer 而不是file.buffer
  • 文件是{ fieldname: 'file', originalname: 'pexels-photo-1004665.jpeg', encoding: '7bit', mimetype: 'image/jpeg' }req.file.buffer 给出错误TypeError: Cannot read property 'buffer' of undefined
  • @jones 我遇到了这个问题。你设法让它工作了吗?
  • @PrivateOmega 嗨,希望一切都好。我有一个非常相似的问题,请看一下。stackoverflow.com/questions/65479245/nodejs-multer-aws-s3
【解决方案2】:

对我来说,更改为以下工作。

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;
  }
 });
};

【讨论】:

    猜你喜欢
    • 2016-04-11
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 2019-10-10
    • 2018-02-14
    • 2016-01-10
    相关资源
    最近更新 更多