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:
Project settings:
Create a project directory and initialize it:
<code class="language-bash">mkdir imageUpload cd imageUpload npm init -y</code>
Install dependencies:
<code class="language-bash">npm install express multer body-parser pg</code>
Create directory structure:
<code>imageUpload/ ├── index.js ├── images/ ├── db/ │ └── db.js └── routes/ └── image_routes.js └── controllers/ └── upload.js</code>
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>
Code implementation:
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>
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>
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>
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>
Test:
Use Postman to send a POST request to /upload/single
or /upload/multiple
, attaching the image file and username data.
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!