Home Web Front-end JS Tutorial Building an Express web App for File Uploads and Dynamic Image Processing on the fly

Building an Express web App for File Uploads and Dynamic Image Processing on the fly

Nov 12, 2024 am 01:15 AM

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:

  1. Express.js - for setting up the server.
  2. Multer - for handling file uploads.
  3. Sharp - for image processing.
  4. 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
Copy after login
Copy after login
Copy after login

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 
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login

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 }));
Copy after login
Copy after login

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 });
Copy after login
Copy after login

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
  });
});
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login

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 
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login

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 
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login
  • 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 }));
Copy after login
Copy after login
  • 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 });
Copy after login
Copy after login
  • 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
  });
});
Copy after login
Copy after login

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

  1. Upload an image via Postman.
  2. Retrieve the uploaded image in the browser using the URL provided by Postman.
  3. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles