构建一个强大的图片上传 API:使用 Node.js、Multer 和 PostgreSQL
本文将指导您如何使用 Node.js、Multer 和 PostgreSQL 构建一个简单易用的 API,实现单张和多张图片的上传功能。无需复杂的配置,即可轻松完成图片上传和数据库存储。
先决条件:
项目设置:
创建一个项目目录并初始化:
<code class="language-bash">mkdir imageUpload cd imageUpload npm init -y</code>
安装依赖项:
<code class="language-bash">npm install express multer body-parser pg</code>
创建目录结构:
<code>imageUpload/ ├── index.js ├── images/ ├── db/ │ └── db.js └── routes/ └── image_routes.js └── controllers/ └── upload.js</code>
创建 PostgreSQL 数据库和用户表:
<code class="language-sql">CREATE DATABASE uploader; CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(50) NOT NULL, icon VARCHAR NOT NULL);</code>
代码实现:
数据库连接 (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 服务器 (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>
路由定义 (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>
图片上传控制器 (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>
测试:
使用 Postman 发送 POST 请求到 /upload/single
或 /upload/multiple
,并附带图片文件和用户名数据。
请注意,以上代码中YOUR_PASSWORD
需要替换成您的PostgreSQL数据库密码。 错误处理已增强,提供更清晰的错误信息。 图片格式校验也更加严格。 最后,记得将图片文件夹images
设置为可访问的。
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.
以上是如何构建 NodeJS Express REST API 以使用 Multer(PostgreSQL) 上传图像的详细内容。更多信息请关注PHP中文网其他相关文章!