是否有任何选项可以使用 multer 功能在 nodejs 中减小图像大小并调整图像大小?

Jag*_*esh 3 javascript node.js multer

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})

var upload = multer({ storage: storage })
Run Code Online (Sandbox Code Playgroud)

我需要调整图像大小并将图像大小压缩到最低并上传到目录中。有帮助吗?

Kay*_*eri 5

您可以为 multer 创建自定义存储引擎。

根据官方文档,自定义存储引擎是公开两个函数的类:_handleFile_removeFile

这是创建自定义存储引擎的官方模板(链接):

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)

    file.stream.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)
}
Run Code Online (Sandbox Code Playgroud)

您可以在将_handleFile函数保存到磁盘之前减小该函数的图像大小。

为了减小图像大小,您可以从各种执行此工作的 npm 模块中进行选择。一些值得检查的模块是Sharp轻量级图像处理器用于 node 的 GraphicsMagick