構建一個強大的圖片上傳 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中文網其他相關文章!