Upload file Node JS
Sabir Sheikh

Sabir Sheikh @sabir_sheikh_cd49d4c419e3

About: Hi, I'm Mohammad Sabir, a passionate software developer with experience in .NET Core, Flutter, Java, and React JS. I love turning ideas into working code and sharing what I learn along the way.

Joined:
May 4, 2025

Upload file Node JS

Publish Date: Jun 12
0 0

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
Enter fullscreen mode Exit fullscreen mode

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'));
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Create a blog.ejs file to display the uploaded file:

<h2>Uploaded Blog Image</h2>
<img src="/<%= image %>" alt="Blog Image">
Enter fullscreen mode Exit fullscreen mode

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

Comments 0 total

    Add comment