1. Initialize Your Project
Create a new Node.js project and install dependencies:
mkdir my-blog
cd my-blog
npm init -y
npm install express multer body-parser ejs
2. Configure Express Server
Set up an Express server with multer for file uploads:
const express = require('express');
const multer = require('multer');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('uploads'));
app.set('view engine', 'ejs');
const storage = multer.diskStorage({
destination: './uploads/',
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
app.post('/upload', upload.single('image'), (req, res) => {
res.render('blog', { image: req.file.filename });
});
app.get('/', (req, res) => {
res.render('index');
});
app.listen(3000, () => console.log('Server running on port 3000'));
3. Create Blog Templates
Create an index.ejs file for the upload form:
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
Create a blog.ejs file to display the uploaded file:
<h2>Uploaded Blog Image</h2>
<img src="/<%= image %>" alt="Blog Image">
4. Run Your Blog
Start the server and access the blog at http://localhost:3000.
Would you like to integrate a database to store blog content dynamically? I can help with that too