Home > Web Front-end > JS Tutorial > How to build NodeJS Express REST API to Upload Image using Multer(PostgreSQL)

How to build NodeJS Express REST API to Upload Image using Multer(PostgreSQL)

Mary-Kate Olsen
Release: 2025-01-25 00:32:12
Original
595 people have browsed it

Build a powerful image upload API: using Node.js, Multer and PostgreSQL

This article will guide you on how to use Node.js, Multer and PostgreSQL to build a simple and easy-to-use API to implement single and multiple image upload functions. Image uploading and database storage can be easily completed without complicated configuration.

Prerequisites:

  • Node.js and PostgreSQL are installed and configured.
  • Familiar with the basic operations of Node.js and PostgreSQL.
  • Postman for API testing.

Project settings:

  1. Create a project directory and initialize it:

    <code class="language-bash">mkdir imageUpload
    cd imageUpload
    npm init -y</code>
    Copy after login
  2. Install dependencies:

    <code class="language-bash">npm install express multer body-parser pg</code>
    Copy after login
  3. Create directory structure:

    <code>imageUpload/
    ├── index.js
    ├── images/
    ├── db/
    │   └── db.js
    └── routes/
        └── image_routes.js
    └── controllers/
        └── upload.js</code>
    Copy after login
  4. Create PostgreSQL database and user tables:

    <code class="language-sql">CREATE DATABASE uploader;
    CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(50) NOT NULL, icon VARCHAR NOT NULL);</code>
    Copy after login

Code implementation:

  1. Database connection (db.js):

    <code class="language-javascript">const { Client } = require('pg');
    const client = new Client({
        user: 'postgres',
        host: 'localhost',
        database: 'uploader',
        password: 'YOUR_PASSWORD', // 请替换为您的数据库密码
        port: 5432,
    });
    client.connect().then(() => console.log("Connected to DB")).catch(err => console.error("数据库连接失败:", err.message));
    module.exports = client;</code>
    Copy after login
  2. Express Server (index.js):

    <code class="language-javascript">const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    const port = process.env.PORT || 4000;
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use('/images', express.static('images')); // 设置静态文件目录
    
    require('./routes/image_routes')(app);
    
    app.listen(port, () => {
        console.log(`服务器运行在端口 ${port}`);
    });</code>
    Copy after login
  3. Route definition (image_routes.js):

    <code class="language-javascript">const express = require('express');
    const uploadController = require('../controllers/upload');
    
    module.exports = (app) => {
        app.post('/upload/single', uploadController.upload.single('icon'), uploadController.uploadSingleImage);
        app.post('/upload/multiple', uploadController.upload.array('icon', 12), uploadController.uploadMultipleImage);
    };</code>
    Copy after login
  4. Image upload controller (upload.js):

    <code class="language-javascript">const multer = require('multer');
    const path = require('path');
    const client = require('../db/db');
    
    const storage = multer.diskStorage({
        destination: (req, file, cb) => cb(null, './images'),
        filename: (req, file, cb) => cb(null, `image-${Date.now()}${path.extname(file.originalname)}`),
    });
    
    const fileFilter = (req, file, cb) => {
        if (!file.originalname.match(/\.(jpg|jpeg|png)$/i)) {
            return cb(new Error('请上传 JPG, JPEG 或 PNG 格式的图片'), false);
        }
        cb(null, true);
    };
    
    exports.upload = multer({ storage, fileFilter });
    
    exports.uploadSingleImage = async (req, res) => {
        try {
            await client.query(`INSERT INTO users (name, icon) VALUES ('${req.body.name}', '${req.file.filename}')`);
            res.json({ statusCode: 200, status: true, message: '图片上传成功' });
        } catch (error) {
            console.error("图片上传失败:", error);
            res.status(500).json({ statusCode: 500, status: false, message: '图片上传失败' });
        }
    };
    
    exports.uploadMultipleImage = async (req, res) => {
        try {
            for (const file of req.files) {
                await client.query(`INSERT INTO users (name, icon) VALUES ('${req.body.name}', '${file.filename}')`);
            }
            res.json({ statusCode: 200, status: true, message: '所有图片上传成功' });
        } catch (error) {
            console.error("图片上传失败:", error);
            res.status(500).json({ statusCode: 500, status: false, message: '图片上传失败' });
        }
    };
    </code>
    Copy after login

Test:

Use Postman to send a POST request to /upload/single or /upload/multiple, attaching the image file and username data.

How to build NodeJS Express REST API to Upload Image using Multer(PostgreSQL)

Please note that YOUR_PASSWORD in the above code needs to be replaced with your PostgreSQL database password. Error handling has been enhanced to provide clearer error messages. Image format verification is also more stringent. Finally, remember to make the images folder images accessible.

This revised response provides a more robust and secure solution, including error handling and improved clarity. Remember to replace placeholders like YOUR_PASSWORD with your actual credentials.

The above is the detailed content of How to build NodeJS Express REST API to Upload Image using Multer(PostgreSQL). For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template