簡介
本篇教學將帶您使用 Node.js 和 JavaScript 實現一個簡易相簿功能,具備圖片上傳、顯示以及查看原圖的功能。我們將利用 Express
框架以及 multer
中介軟體處理文件上傳,並使用 EJS 作為模板引擎來呈現網頁內容。
實現目標
- 相簿首頁:顯示所有已上傳的圖片。
- 圖片上傳:提供用戶上傳圖片的功能。
- 圖片查看:可點擊縮圖查看原圖。
開始前準備
所需環境
- Node.js 安裝(下載 Node.js)。
- 文本編輯器(建議使用 VS Code)。
專案結構
建立以下目錄與文件:
photo-album/
├── public/
│ ├── images/ # 儲存上傳的圖片
│ └── styles/ # 儲存 CSS 樣式
├── views/ # 儲存 EJS 模板
│ ├── index.ejs # 相簿首頁模板
│ └── upload.ejs # 上傳圖片頁面模板
├── app.js # 主程式文件
└── package.json # 專案描述文件
初始化專案
- 在終端中執行以下指令來初始化專案並安裝必要套件:
npm init -y
npm install express multer ejs
- 安裝完成後,專案的目錄結構將包含一個
node_modules
資料夾。
撰寫程式碼
1. app.js
撰寫核心伺服器邏輯:
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const app = express();
const PORT = 3000;
// 設定靜態檔案目錄
app.use(express.static('public'));
// 設定模板引擎
app.set('view engine', 'ejs');
// 設定 multer 儲存選項
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './public/images');
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`);
},
});
const upload = multer({ storage });
// 相簿首頁
app.get('/', (req, res) => {
const imagesPath = path.join(__dirname, 'public/images');
fs.readdir(imagesPath, (err, files) => {
if (err) return res.status(500).send('無法讀取圖片');
res.render('index', { images: files });
});
});
// 上傳圖片頁面
app.get('/upload', (req, res) => {
res.render('upload');
});
// 處理圖片上傳
app.post('/upload', upload.single('image'), (req, res) => {
res.redirect('/');
});
// 啟動伺服器
app.listen(PORT, () => {
console.log(`伺服器正在執行於 http://localhost:${PORT}`);
});
2. 模板文件
views/index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>我的相簿</title>
<link rel="stylesheet" href="/styles/style.css">
</head>
<body>
<h1>我的相簿</h1>
<a href="/upload">上傳圖片</a>
<div class="gallery">
<% images.forEach(image => { %>
<a href="/images/<%= image %>" target="_blank">
<img src="/images/<%= image %>" alt="<%= image %>" width="200">
</a>
<% }) %>
</div>
</body>
</html>
views/upload.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上傳圖片</title>
</head>
<body>
<h1>上傳圖片</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="image" required>
<button type="submit">上傳</button>
</form>
<a href="/">返回相簿</a>
</body>
</html>
3. CSS 樣式
在 public/styles/
資料夾中新增 style.css
:
body {
font-family: Arial, sans-serif;
}
.gallery {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.gallery img {
border: 1px solid #ddd;
border-radius: 5px;
padding: 5px;
transition: transform 0.2s;
}
.gallery img:hover {
transform: scale(1.1);
}
啟動專案
- 在終端執行以下指令啟動伺服器:
node app.js
- 打開瀏覽器,訪問 http://localhost:3000。
延伸功能
- 分類管理:為每張圖片加入分類功能。
- 檔案限制:限制檔案類型與大小(如 JPG/PNG,不超過 5MB)。
- 圖片刪除:增加圖片刪除功能。
- 部署:將應用程式部署至伺服器(如 Vercel 或 Heroku)。
如果有任何問題或想添加新功能,歡迎討論!