Let’s configure multer and create some functions.
const multer = require("multer");
const multerStorage = multer.memoryStorage();
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
cb("Please upload only images.", false);
}
};
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter
});
const uploadFiles = upload.array("images", 10); // limit to 10 images
const uploadImages = (req, res, next) => {
uploadFiles(req, res, err => {
if (err instanceof multer.MulterError) { // A Multer error occurred when uploading.
if (err.code === "LIMIT_UNEXPECTED_FILE") { // Too many images exceeding the allowed limit
// ...
}
} else if (err) {
// handle other errors
}
// Everything is ok.
next();
});
};
In the code above, we’ve done these steps:
– First, import multer module.
– Next, configure multer to store images in memory as a buffer so that we could then use it later by other processes (resize the images before saving them to disk).
– We also define a filter to only allow images to pass.
– Then use multer object to create uploadFiles function with the field images and the max count. The array of files will be stored in req.files.
– We catch errors by calling the uploadFiles middleware function, if there is no error, call next().
Resizing images using Sharp
Now we’re gonna process all of uploaded images (which are in memory).
Let me explain the code.
– We import sharp module.
– The resizeImages will be an async function in that:
We check if there are no images uploaded, move straight to the next middleware
For each image, we return a Promise, we need all of the Promises done before calling next(). So we get an array of all of these Promises using array.map() then put it in Promise.all() function.
We process every image in the images array using resize() method, then change the format (with file extension) to jpeg with toFormat() and save it to disk using toFile() method.
The Route Handler Functions
We write all middleware functions above in a Controller called upload.
We use Express Router to handle POST action to "/multiple-upload" endpoint.
You can see that we insert uploadImages and resizeImages, then uploadController.getResult. This is because we will process images before showing the result message.
Demo
Open browser for the app:
Choose some images to upload & resize:
Click on Submit button, if the process is successful, browser shows the uploaded images:
Check the upload folder, you can see the resized images:
If you choose the file without image format, or the images you want to upload exceeds the allowed amount, the browser will show the messages.
Practice: Upload & Resize multiple images with Node.js
Now I’m gonna show you how to build this Node.js application step by step.
Project Structure
This is our project structure:
– upload: the folder for storing uploaded images.
– views/index.html: contains HTML form for user to upload images.
– routes/web.js: defines routes for endpoints that is called from views, use controllers to handle requests.
– controllers:
home.js returns views/index.html
upload.js handles upload & resize multiple images with middleware functions.
The HTML code is easy to understand, the jQuery script shows preview of the chosen images.
We also use Bootstrap to make the UI more comfortable to read.
Create Controller for the view
Under controllers folder, create home.js file.
const path = require("path");
const home = (req, res) => {
return res.sendFile(path.join(`${__dirname}/../views/index.html`));
};
module.exports = {
getHome: home
};
Create Controller for processing Images
This is the main code of our Node.js project. The Upload Controller uses both multer & sharp module.
In the resizeImages function, we:
– get each image name and create new name for it with jpeg extension.
– resize to 640x320
– change the image format to jpeg
– set the quality to 90% of the original image
– save the image file to upload folder
Define routes
We define routes in routes/web.js like this.
There are 2 routes:
– GET: Home page for the upload form.
– POST "/multiple-upload" to use three uploadController functions.