Upload & resize multiple images in Node.js using Express, Multer, Sharp
Uploading multiple images using Multer
Upload multiple images View
In HTML, we create a form with following elements:
action="/multiple-upload"enctype="multipart/form-data"multipleinput
<form
action="/multiple-upload"
method="POST"
enctype="multipart/form-data">
...
<input type="file" multiple>
...
</form>Using Multer to upload multiple Images
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 thePromisesdone before callingnext(). So we get an array of all of thesePromisesusingarray.map()then put it inPromise.all()function.We process every image in the
imagesarray usingresize()method, then change the format (with file extension) tojpegwith toFormat() and save it to disk usingtoFile()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.jsreturnsviews/index.htmlupload.jshandles upload & resize multiple images with middleware functions.
– server.js: initializes routes, runs Express app.
Setup Node.js modules
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:
uploadImagesresizeImagesgetResult
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.
Last updated
Was this helpful?