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.
– 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.
Change current directory to the root folder of our project, then install Express, Multer, Sharp with the following command:
Create View for uploading multiple images
In views folder, create index.html with the HTML and Javascript code as below:
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.
Create Controller for processing Images
This is the main code of our Node.js project. The Upload Controller uses both multer & sharp module.
We’re gonna export 3 middleware functions:
uploadImages
resizeImages
getResult
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.
Create Express app server
Finally, we only need to create an Express server.
server.js
Run the app
Before running this Node.js app, you must create upload folder in the project root folder.
Run following command:
node src/server.js
If everything is ok, the console shows:
Open browser with url http://localhost:3000/ and you can check the result now.