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,349
  • 8
  • 30
  • 47
Manimaran
  • 383
  • 2
  • 6
  • 19

3 Answers3

8

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,723
  • 32
  • 48
  • "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
  • @AndréWerlang Hi, i know its been a while since this answer but can you please have a look at my question.https://stackoverflow.com/questions/65465145/uploading-multiple-images-with-multer-to-aws-s3 – kd12345 Dec 28 '20 at 04:59
5

Try this code Resize Image Upload Using Multer

Install Express and Multer Dependencies

npm install express multer --save npm install sharp --save

Create Server.js File

const express = require('express');
const multer = require('multer');
const path = require('path');
const sharp = require('sharp');
const fs = require('fs');
const app = express();
const port = 3000
   
const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, 'uploads/');
    },
   
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});
   
var upload = multer({ storage: storage })
   
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});
   
app.post('/', upload.single('image'),async (req, res) => {
       const { filename: image } = req.file;
       
       await sharp(req.file.path)
        .resize(200, 200)
        .jpeg({ quality: 90 })
        .toFile(
            path.resolve(req.file.destination,'resized',image)
        )
        fs.unlinkSync(req.file.path)
       
       res.redirect('/');
});
   
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

Create Form

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Node JS Resize Image Upload Using Multer Sharp With Example - phpcodingstuff.com</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <h1>Node JS Resize Image Upload Using Multer Sharp With Example - phpcodingstuff.com</h1>
    <form action="/" enctype="multipart/form-data" method="post">
      <input type="file" name="image" accept='image/*'>
      <input type="submit" value="Upload">
    </form>  
  </body>
</html>

Enjoy this code

Ajay kumar
  • 105
  • 1
  • 5
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