How to resize image size in nodejs using multer

后端 未结 1 362
既然无缘
既然无缘 2021-01-18 16:54

Multer have already limit size property. This property only restrict the image. Not resize the image. My question is suppose image is greater than \"limit size\", how to res

相关标签:
1条回答
  • 2021-01-18 17:56

    It depends on whether you want to store the resized image as well.

    In any case, you'll use a library to handle the resize operation. sharp is a very good option.

    Resize in a route handler(after file is stored to disk):

    sharp(req.file).resize(200, 200).toBuffer(function(err, buf) {
      if (err) return next(err)
    
      // Do whatever you want with `buf`
    })

    Other option would be creating your own storage engine, in this case you'll receive the file data, resize, then store to disk (copied from https://github.com/expressjs/multer/blob/master/StorageEngine.md):

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

    0 讨论(0)
提交回复
热议问题