亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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

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

  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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How does garbage collection work in JavaScript? How does garbage collection work in JavaScript? Jul 04, 2025 am 12:42 AM

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. Jul 08, 2025 pm 02:27 PM

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

React vs Angular vs Vue: which js framework is best? React vs Angular vs Vue: which js framework is best? Jul 05, 2025 am 02:24 AM

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

Understanding Immediately Invoked Function Expressions (IIFE) in JavaScript Understanding Immediately Invoked Function Expressions (IIFE) in JavaScript Jul 04, 2025 am 02:42 AM

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

What is the cache API and how is it used with Service Workers? What is the cache API and how is it used with Service Workers? Jul 08, 2025 am 02:43 AM

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Jul 08, 2025 am 02:40 AM

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

See all articles