10

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 resize that image ?

var storageOptions = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'useravatars/')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
});

var avatarUpload = multer({
    storage: storageOptions,
    limits: {
        fileSize: 1000000
    }
}).single("avatar");
TGrif
  • 5,725
  • 9
  • 31
  • 52
Manimaran
  • 405
  • 2
  • 8
  • 20

2 Answers2

9

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)
}
André Werlang
  • 5,839
  • 1
  • 35
  • 49
  • "sharp Module" not able to install because cmd throw following error sharp@0.18.4 install: `node-gyp rebuild` Exit status 1 Failed at the sharp@0.18.4 install script 'node-gyp rebuild'. – Manimaran Nov 24 '17 at 11:31
  • If the last line of output is OK, then it's alright – André Werlang Nov 24 '17 at 12:05
0
const path = require("path");
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, "/uploads"));
  },
  filename: function (req, file, cb) {
    cb(null, uuid.v4() + `${path.extname(file.originalname)}`);
  }
});

const limits = {
  fields: 10,
  fileSize: 500 * 1024,
  files: 1,
};

const upload = multer({ storage, limits });
const baseUrl = "http://localhost:3000/files/";
router.post("/upload", upload.single("file"), async (ctx, next) => {
  ctx.body = {
    code: 1,
    data: baseUrl + ctx.file.filename,
  };
});
Viwat Vat
  • 1
  • 1
  • From Review: Hi, code-only or command-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to people with similar issues. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). – sɐunıɔןɐqɐp Jun 29 '21 at 10:03