Node.js Image Upload, Processing and Resizing using Sharp package
Last Updated :
04 Apr, 2023
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:
- Thumbnail
- Low resolution for previews, etc.
- The original high resolution for the actual product.
Prerequisites:
- Node.js basics
- Routes handling in express.js
Modules used: sharp, Multer
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
Multer setup:
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 to the official documentation at Multer
javascript
// Importing the module
const multer = require('multer');
// Setting up a middleware specifying the
// destination for storing the images
const upload = multer({dest : './images'})
Since multer works with form data, you need to ensure the upload is via a form with configuration as multipart/form-data.
Filename: app.js
javascript
const express = require('express');
const bodyparser = require('body-parser');
const fs = require('fs');
const multer = require('multer');
const sharp = require('sharp');
const upload = multer({dest : './images'})
// Initialize the express object
const app = express();
// Use body-parser to parse incoming data
app.use(bodyparser.urlencoded({extended : true}))
// Use the upload middleware containing
// our file configuration, with the name
// of input file attribute as "avatar"
// to the desired configuration.
app.post('/upload', upload.single("avatar"), (req, res)=>
{
fs.rename(req.file.path, './images/avatar.jpg', (err)=>{
console.log(err);
})
return res.json("File Uploaded Successfully!");
});
app.listen(3000, ()=>{
console.log("Server Running!")
})
Steps to run the above code:
Run the app.js file using the following command:
node app.js
After executing the above command, you will see the following output:
Server Running!
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:
javascript
// Configuring thumbnail image
sharp(__dirname + '/images/avatar.jpg').resize(200,200)
.jpeg({quality : 50}).toFile(__dirname
+ '/images/avatar_thumb.jpg');
// Configuring Preview Image
sharp(__dirname + '/images/avatar.jpg').resize(640,480)
.jpeg({quality : 80}).toFile(__dirname
+ '/images/avatar_preview.jpg');
So all things are set, the final app.js will be as follows:
Filename: app.js
javascript
const express = require('express');
const bodyparser = require('body-parser');
const fs = require('fs');
const multer = require('multer');
const sharp = require('sharp');
const upload = multer({dest : './images'})
const app = express();
app.use(bodyparser.urlencoded({extended : true}))
app.post('/upload', upload.single("avatar"), (req, res)=>
{
fs.rename(req.file.path, './images/avatar.jpg', (err)=>{
console.log(err);
})
sharp(__dirname + '/images/avatar.jpg').resize(200,200)
.jpeg({quality : 50}).toFile(__dirname
+ '/images/avatar_thumb.jpg');
sharp(__dirname + '/images/avatar.jpg').resize(640,480)
.jpeg({quality : 80}).toFile(__dirname
+ '/images/avatar_preview.jpg');
return res.json("File Uploaded Successfully!");
});
app.listen(3000, ()=>{
console.log("Server Running!")
})
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/
Similar Reads
Upload and Retrieve Image on MongoDB using Mongoose
Prerequisites: For getting started with this you should have some familiarity with NodeJS, ExpressJS, MongoDB, and Mongoose.NodeJS: It is a free open-source server environment that uses JavaScript on the server and runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.).It uses asynchronous
4 min read
How to Upload File with Progress Bar using Node.js ?
Uploading files in NodeJS involves transferring files from the client's location to the server's location. A progress bar is a visual component that displays the percentage of the total file upload. In this tutorial, we will create a local server and demonstrate how to upload files to a destination
4 min read
How to Upload Image and Preview it Using ReactJS?
In React, uploading and previewing images improve the user experience of the application. It's typical for online apps to provide image upload capability that enables users to choose and upload photographs. We simply upload a photo from our local device to our React Project and preview it using a st
2 min read
CRUD Operations and File Upload using Node.js and MongoDB
Within the computer programming world, CRUD is an elision for the 4 operations Create, Read, Update, and Delete. Create, Read, Update, and Delete (CRUD) are the four basic functions that models should be able to do, at most. In RESTful applications, CRUD often corresponds to the HTTP methods like  P
15 min read
How to Upload Single/Multiple Image to Cloudinary using Node.js ?
Uploading images to Cloudinary from a Node.js application is a common task when you need to manage and store images in the cloud. Cloudinary is a cloud-based service that provides comprehensive solutions for image and video management, including upload, storage, manipulation, and delivery.Approachto
4 min read
Preview an image before uploading using jQuery
Previewing an image before uploading using jQuery allows users to see the selected image on the webpage before submitting it to the server. This enhances user experience by providing immediate visual feedback, ensuring the correct image is chosen. There are several methods to preview an image before
3 min read
Node.js Server Side Rendering (SSR) using EJS
Server-side rendering (SSR) is a popular technique for rendering a normally client-side-only single-page app (SPA) on the server and then sending a fully rendered page to the client. The client's JavaScript bundle can then take over and the SPA can operate as normal. SSR technique is helpful in situ
3 min read
How to upload an image using HTML and JavaScript in firebase ?
Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud st
3 min read
How to upload files in firebase storage using ReactJS ?
Firebase Storage is a powerful cloud storage solution provided by Google's Firebase platform. It allows developers to store and retrieve user-generated content, such as images, videos, and other files, in a secure and scalable manner. In this article, we will explore how to upload files to Firebase
2 min read
How To Create React Multiple File Upload Using NextJS And Typescript?
In this article, we'll explore how to implement a file upload feature in a Next.js application using React. We'll leverage the react-dropzone library to create a user-friendly interface for uploading multiple files. Additionally, we'll integrate TypeScript for type safety and ESLint for code linting
2 min read