如何使用 multer 上传文件并在上传前优化它们 - NodeJs

How upload files and optimize them before upload using multer - NodeJs

我正在使用 Nodejs、react 和 mongo 做一个社交网络。我正在使用 multer 上传图片,但 我需要在上传到目录之前优化它们。

穆尔特

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, "./uploads/publications");
  },

  filename(req, file = {}, cb) {
    const { originalname } = file;
    const fileExtension = (originalname.match(/\.+[\S]+$/) || [])[0];
    crypto.pseudoRandomBytes(16, function (err, raw) {
      cb(null, raw.toString("hex") + Date.now() + fileExtension);
    });
  },
});

var mul_upload = multer({ dest: "./uploads/publications", storage });

路线

app.post(
  "/publication",
  [md_auth.ensureAuth, mul_upload.single("image")],
  PublicationController.savePublication
);

是否可以在上传前压缩和优化图片?

对于reactJs 这是一个 npm 包

npm i react-image-file-resizer

对于 NodeJs

npm i react-image-file-resizer

您需要使用 npm 包。 sharp 这可能是一个非常好的选择。

const sharp = require('sharp')
sharp(req.file).resize(200, 200).toBuffer(function(err, buf) {
  if (err) return next(err)

  //  you can do anything with the buffer
}) 

使用multer可以实现自定义存储功能。您可以查看 here 如何操作。我在这里添加示例代码:

var fs = require('fs')

function getDestination(req, file, cb) {
  cb(null, '/dev/null')
}

function MyCustomStorage(opts) {
  this.getDestination = (opts.destination || getDestination)
}

MyCustomStorage.prototype._handleFile = function _handleFile(req, file, cb) {
  this.getDestination(req, file, function(err, path) {
    if (err) return cb(err)

    var outStream = fs.createWriteStream(path)
    var resizer = sharp().resize(200, 200).png()

    file.stream.pipe(resizer).pipe(outStream)
    outStream.on('error', cb)
    outStream.on('finish', function() {
      cb(null, {
        path: path,
        size: outStream.bytesWritten
      })
    })
  })
}

MyCustomStorage.prototype._removeFile = function _removeFile(req, file, cb) {
  fs.unlink(file.path, cb)
}

module.exports = function(opts) {
  return new MyCustomStorage(opts)
}