Often in our web applications, we need to store multiple forms and formats of images, in the form of a profile picture or an image for a product in an e-commerce prototype. In most of our cases, we need to store images compressed to multiple sizes, retaining the quality. For example, for a product at an e-commerce site, we would require storing 3 versions of a product image:
- Low resolution for previews, etc.
- The original high resolution for the actual product.
- Node.js basics
- Routes handling in express.js
According to the official npm documentation, The typical use case for sharp is to convert large images in common formats to smaller, web-friendly JPEG, PNG, and WebP images of varying dimensions.
Initialize npm in an empty directory to begin with the following command:
npm init -y
Install the required modules with the following command:
npm install express --save npm install body-parser --save npm install sharp --save npm install multer --save
To upload files, we need to configure multer as a middleware to be passed. To set up multer, we need to add the following code to our application.
Note: For additional usage and to know more about uploads and multer, you can refer the official documentation at Multer
Since multer works with form-data, you need to ensure the upload is via a form with configuration as multipart/form-data.
Steps to run above code:
- Run app.js file using the following command:
After executing above command, you will see the following output:
- Send a POST request to https://localhost:3000/upload using Postman. You need to pass “avatar” as KEY and picture as VALUE.
- After hitting the request, an image directory will be created with our desired image.
Processing Image using Sharp: We will be processing images via a sharp package. To create multiple instances with different properties, we use the following code:
So all things are set, final app.js will be as following:
Upon running the server and sending the same request as before, you will get your all uploaded images in the image directory with the desired configuration as shown below:
Additional Sharp Options: https://sharp.pixelplumbing.com/