Multer-sharp-resizer, Resize one image or multiple images to multiple sizes with node.js, express.js, multer.js, sharp.js and multer-sharp-resizer.js

Mohammad Oftadeh
4 min readJun 1, 2020
Resize one image or multiple images to multiple sizes with nodejs, multer-sharp-resizer

In this article, I’m going to teach you how to upload images in node.js with multer.js, sharp.js, express.js, and multer-sharp-resizer.js packages along with resizing.

You can see this video instead of reading article:

Node.js uploading image with multer and multer-sharp-resizer, sharp.js

Brief introduction of the packages used:

express.js

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

multer.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.

sharp.js

The typical use case for this high speed Node.js module is to convert large images in common formats to smaller, web-friendly JPEG, PNG and WebP images of varying dimensions.

multer-sharp-resizer.js

Resize one image or multiple images to multiple sizes with node.js, express.js, multer.js and sharp.js

Let’s get started:

Well, now we want to upload our images in two ways, one as a single and the other as a group.

We perform the following steps in order:

Making new folder :

mkdir node-upload
cd node-upload

Create package.json file:

npm init -y

Install packages:

with npm:

npm install express multer multer-sharp-resizer

or yarn:

yarn add install express multer multer-sharp-resizer

Now create index.js file in the root project.

Well, now that everything is in order, it’s time to implement. Then create node server with express:

const express = require(“express”);
const app = express();
const port = 8000;
app.listen(port, () => console.log(“server running on port 8000…”));

After that add multer and multer-sharp-resizer packages to index.js file:

const express = require(“express”);
const multer = require("multer");
const MulterSharpResizer = require("multer-sharp-resizer");
const app = express();const port = 8000;
app.listen(port, () => console.log(“server running on port 8000…”));

Add a middleware to handle static files in the public directory:

const express = require(“express”);
const multer = require("multer");
const MulterSharpResizer = require("multer-sharp-resizer");
const app = express();app.use(express.static(`${__dirname}/public`));const port = 8000;
app.listen(port, () => console.log(“server running on port 8000…”));

Add multer.memoryStorage:

The memory storage engine stores the files in memory as Buffer objects. It doesn't have any options.

const express = require(“express”);
const multer = require("multer");
const MulterSharpResizer = require("multer-sharp-resizer");
const app = express();app.use(express.static(`${__dirname}/public`));const multerStorage = multer.memoryStorage();const port = 8000;
app.listen(port, () => console.log(“server running on port 8000…”));

When using memory storage, the file info will contain a field called buffer that contains the entire file.

Add fileFilter

Set this to a function to control which files should be uploaded and which should be skipped. The function should look like this:(To check if the files are the image or not)

const express = require(“express”);
const multer = require("multer");
const MulterSharpResizer = require("multer-sharp-resizer");
const app = express();app.use(express.static(`${__dirname}/public`));const multerStorage = multer.memoryStorage();// Filter files with multer
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
cb("Not an image! Please upload only images.", false);
}
};
const port = 8000;
app.listen(port, () => console.log(“server running on port 8000…”));

If you want more control over your uploads, you’ll want to use the storage option instead of dest:

const express = require(“express”);
const multer = require("multer");
const MulterSharpResizer = require("multer-sharp-resizer");
const app = express();app.use(express.static(`${__dirname}/public`));const multerStorage = multer.memoryStorage();// Filter files with multer
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
cb("Not an image! Please upload only images.", false);
}
};
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter,
});
const port = 8000;
app.listen(port, () => console.log(“server running on port 8000…”));

Create resizeImagesGalleryFunc() function for upload and resize multiple images and then add these lines:

const express = require(“express”);
const multer = require("multer");
const MulterSharpResizer = require("multer-sharp-resizer");
const app = express();app.use(express.static(`${__dirname}/public`));const multerStorage = multer.memoryStorage();// Filter files with multer
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
cb("Not an image! Please upload only images.", false);
}
};
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter,
});
// upload multiple images example
// resize multiple images function
const resizeImagesGalleryFunc = async (req, res) => {
try {const today = new Date();
const year = today.getFullYear();
const month = `${today.getMonth() + 1}`.padStart(2, "0");
const filename = `gallery-${Date.now()}.jpeg`;const sizes = [
{
path: "original",
width: null,
height: null,
},
{
path: "large",
width: 800,
height: 800,
},
{
path: "medium",
width: 300,
height: 300,
},
{
path: "thumbnail",
width: 100,
height: 100,
},
];
const uploadPath = `./public/uploads/${year}/${month}`;const fileUrl = `${req.protocol}://${req.get("host"
)}/uploads/${year}/${month}`;
// sharp options
const sharpOptions = {
fit: "contain",
background: { r: 255, g: 255, b: 255 },
};
// create a new instance of MulterSharpResizer and pass params
const resizeObj = new MulterSharpResizer(
req,
filename,
sizes,
uploadPath,
fileUrl,
sharpOptions
);
// call resize method for resizing files
resizeObj.resize();
// get details of uploaded files
const images = resizeObj.getData();
res.status(200).json({
status: "success",
data: {
gallery: images,
},
});
} catch (err) {
console.log(err);
}
};
const port = 8000;
app.listen(port, () => console.log(“server running on port 8000…”));

and now you can upload and resizing files with multer and multer-sharp-resizer.

Outputs of above examples:

// example uploading multiple files
// result: uploaded multiple images with resizing
{
"status": "success",
"data": {
"gallery": [
{
"originalname": "kal-visuals-b1Hg7QI-zcc-unsplash.jpg",
"original": {
"filename": "gallery-1590999763786-0-original.jpeg",
"path": "http://127.0.0.1:8000/uploads/2020/06/original/gallery-1590999763786-0-original.jpeg"
},
"large": {
"filename": "gallery-1590999763786-0-large.jpeg",
"path": "http://127.0.0.1:8000/uploads/2020/06/large/gallery-1590999763786-0-large.jpeg"
},
"medium": {
"filename": "gallery-1590999763786-0-medium.jpeg",
"path": "http://127.0.0.1:8000/uploads/2020/06/medium/gallery-1590999763786-0-medium.jpeg"
},
"thumbnail": {
"filename": "gallery-1590999763786-0-thumbnail.jpeg",
"path": "http://127.0.0.1:8000/uploads/2020/06/thumbnail/gallery-1590999763786-0-thumbnail.jpeg"
}
},
......
{
]
}
}

For more example and documentation: see multer-sharp-resizer doc.

--

--

Mohammad Oftadeh

Helping companies to implement and optimize their systems is something I do alongside other services.