


Building an Express web App for File Uploads and Dynamic Image Processing on the fly
Guide: Building an Express web app for File Uploads and Dynamic Image Processing
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.
Prerequisites
Before we begin, ensure that you have Node.js and npm installed. We will use the following libraries in this tutorial:
- Express.js - for setting up the server.
- Multer - for handling file uploads.
- Sharp - for image processing.
- CORS - to allow cross-origin requests.
Step 1: Setting Up the Project
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
Create the necessary directories
We will need two directories:
- original-image to store the original uploaded images.
- transform-image to store the processed images.
Create these directories by running:
mkdir original-image transform-image
Step 2: Set Up the Express Server
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:
- CORS to allow cross-origin requests.
- express.json() and express.urlencoded() to parse incoming request data.
Step 3: Configure Multer for File Uploads
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:
- The uploaded files are stored in the original-image folder.
- Each file gets a unique name based on the current timestamp and a random number.
Step 4: Create the File Upload Endpoint
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:
- Receives a single file upload (with the field name file).
- Returns the URL of the uploaded file.
Step 5: Serve the Uploaded Files
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:
- Retrieves the file from the db map based on the filename.
- Processes the image if resizing, format conversion, or quality adjustments are specified.
- Caches the processed images to improve performance.
Step 6: Process Images with Sharp
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:
- Resizes the image based on the h (height) and w (width) parameters.
- Converts the image format based on the f parameter (JPEG, PNG, WebP, etc.).
- Adjusts the image quality based on the q parameter (optional).
- Saves the processed image in the transform-image folder.
Step 7: Start the Server
Finally, start the server by adding the following code:
mkdir original-image transform-image
This will start the server on port 3000.
Step 8: Testing the Server
1. Testing File Upload with Postman
To test the file upload functionality using Postman, follow these steps:
1.1 Open Postman
Launch Postman on your computer. If you don't have Postman installed, you can download it here.
1.2 Create a POST Request
- Set the request type to POST.
- In the URL field, enter: http://localhost:3000/upload.
1.3 Add the File in the Body
- Select the Body tab.
- Choose the form-data option.
- In the form, set the key to file (this must match the field name in your multer configuration).
- Click the Choose Files button and select an image file from your computer.
1.4 Send the Request
- Click Send.
- If the upload is successful, you should receive a response with the URL of the uploaded image.
Example Response:
mkdir image-upload-server cd image-upload-server npm init -y
2. Testing Image Retrieval and Processing via Browser
Now, let's test retrieving the image with transformations using the Browser.
2.1 Get the Uploaded Image
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.
3. Testing Image Transformations with Query Parameters
Now, let's test dynamic image transformations by appending query parameters for resizing, format conversion, and quality adjustment.
3.1 Add Query Parameters for Transformation
In your browser, append query parameters to the image URL to test transformations. Here are some examples:
- Resize the image to width 200px and height 300px:
mkdir original-image transform-image
- Convert the image to PNG format:
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 }));
- Convert the image to WebP format with 90% quality:
// 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 });
- Resize the image to width 400px, height 500px, and convert to JPEG with 80% quality:
// 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 }); });
3.2 Expected Behavior
- When you access any of the URLs with the query parameters, the server will process the image accordingly.
- If the image has been processed before with the same parameters, it will serve the cached version.
- If it hasn’t been processed yet, it will process the image (resize, convert format, adjust quality) and save it in the transform-image folder for future requests.
The browser will display the processed image, and you can confirm if the transformation has been applied correctly.
Example Workflow
- Upload an image via Postman.
- Retrieve the uploaded image in the browser using the URL provided by Postman.
- Modify the URL in the browser by adding query parameters like ?h=300&w=200 to see resizing in action or ?f=webp&q=90 for format conversion.
Conclusion
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!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.