Home > Article > Web Front-end > Building an Express web App for File Uploads and Dynamic Image Processing on the fly
In this tutorial, we will show you how to build a server with Express.js that handles file uploads and performs dynamic image processing like resizing, format conversion, and quality adjustments using Sharp.
Before we begin, ensure that you have Node.js and npm installed. We will use the following libraries in this tutorial:
Start by creating a new directory for your project:
mkdir image-upload-server cd image-upload-server npm init -y
This will create a new project folder and initialize a package.json file.
You can install all dependencies by running:
npm install express multer sharp cors
We will need two directories:
Create these directories by running:
mkdir original-image transform-image
Now, let's set up the basic server using Express.js. Create a file called index.js in the root of your project and add the following code to set up the server:
const express = require('express'); const cors = require('cors'); const multer = require('multer'); const path = require('path'); const sharp = require('sharp'); const fs = require('fs'); const app = express(); // Middleware for CORS and JSON parsing app.use(cors()); app.use(express.json()); app.use(express.urlencoded({ extended: true }));
This basic setup includes:
We will use Multer to handle file uploads. Multer allows us to store uploaded files in a specified directory.
Add the following code to configure Multer:
// Configure multer for file storage const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'original-image'); // Ensure the 'original-image' directory exists }, filename: function (req, file, cb) { const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9); cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname)); } }); const upload = multer({ storage: storage });
This setup ensures that:
Next, create a POST endpoint for file uploads. The user will send a file to the server, and the server will store the file in the original-image directory.
Add the following code to handle the file upload:
// File upload endpoint app.post('/upload', upload.single('file'), (req, res) => { const file = req.file; if (!file) { return res.status(400).send({ message: 'Please select a file.' }); } const url = `http://localhost:3000/${file.filename}`; // Store file path with original filename as the key db.set(file.filename, file.path); res.json({ message: 'File uploaded successfully.', url: url }); });
This endpoint does the following:
Now, let's create a GET endpoint to serve the uploaded files. If any query parameters are provided (for example, resizing, format conversion), the server will process the image accordingly.
Add the following code to serve the uploaded files:
mkdir image-upload-server cd image-upload-server npm init -y
This endpoint:
The Sharp library will allow us to perform various transformations on the images, such as resizing, format conversion, and quality adjustments.
Add the processImage function that handles these transformations:
npm install express multer sharp cors
This function:
Finally, start the server by adding the following code:
mkdir original-image transform-image
This will start the server on port 3000.
To test the file upload functionality using Postman, follow these steps:
Launch Postman on your computer. If you don't have Postman installed, you can download it here.
Example Response:
mkdir image-upload-server cd image-upload-server npm init -y
Now, let's test retrieving the image with transformations using the Browser.
To retrieve the image, simply open your browser and navigate to the URL you received after uploading the file. For example, if the response URL was:
npm install express multer sharp cors
Just type this URL in your browser's address bar and hit Enter. You should see the original image displayed.
Now, let's test dynamic image transformations by appending query parameters for resizing, format conversion, and quality adjustment.
In your browser, append query parameters to the image URL to test transformations. Here are some examples:
mkdir original-image transform-image
const express = require('express'); const cors = require('cors'); const multer = require('multer'); const path = require('path'); const sharp = require('sharp'); const fs = require('fs'); const app = express(); // Middleware for CORS and JSON parsing app.use(cors()); app.use(express.json()); app.use(express.urlencoded({ extended: true }));
// Configure multer for file storage const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'original-image'); // Ensure the 'original-image' directory exists }, filename: function (req, file, cb) { const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9); cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname)); } }); const upload = multer({ storage: storage });
// File upload endpoint app.post('/upload', upload.single('file'), (req, res) => { const file = req.file; if (!file) { return res.status(400).send({ message: 'Please select a file.' }); } const url = `http://localhost:3000/${file.filename}`; // Store file path with original filename as the key db.set(file.filename, file.path); res.json({ message: 'File uploaded successfully.', url: url }); });
The browser will display the processed image, and you can confirm if the transformation has been applied correctly.
This image upload and processing server provides a robust solution for handling image uploads, transformations, and retrievals. Using Multer for file handling and Sharp for image processing, it supports resizing, format conversion, and quality adjustments through query parameters. The system efficiently caches processed images to optimize performance, ensuring fast and responsive image delivery. This approach simplifies image management for applications requiring dynamic image transformations, making it a versatile tool for developers.
The above is the detailed content of Building an Express web App for File Uploads and Dynamic Image Processing on the fly. For more information, please follow other related articles on the PHP Chinese website!