Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize image size in nodejs using multer

Tags:

node.js

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");
like image 827
Manimaran Avatar asked Nov 23 '17 11:11

Manimaran


People also ask

How do I resize an image in node JS?

NodeJS – Resize() is an inbuilt function that is used to resize the images to the desired size. We can use resize to set the height and width using a 2-pass bilinear algorithm. It can resize an image into any size as declared by the user. We can take input from the user or resize it into fixed Width*Height size.

How do you use a sharp multer?

const express = require('express') const multer = require('multer') const sharp = require('sharp') const storage = require('./upload-config') const upload = multer(storage) const path = require('path') const fs = require('fs') const app = express() const router = new express.

What is the use of multer in node JS?

Multer is a node. js middleware for handling multipart/form-data , which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.


2 Answers

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)
}
like image 125
André Werlang Avatar answered Oct 20 '22 00:10

André Werlang


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

like image 24
Ajay kumar Avatar answered Oct 20 '22 01:10

Ajay kumar