Skip to main content

Image Upload by using Node Js and Multer

 Image Upload by using Node Js and Multer

Require package

const const multer = require('multer')
const path = require('path')multer = require('multer')
const path = require('path')


For Save in Folder  Do static path 

app.use(express.static(__dirname + './public'));
app.use('/uploads', express.static('uploads'));


Multer part,Multer middleware 

const storage = multer.diskStorage({
    // Destination to store image     
    destination: (req,file,cb)=>{
cb (null , "./uploads")
    } ,
      filename: (req, file, cb) => {
        // console.log(file)
          cb(null,file.fieldname + '_' + Date.now() 
             + path.extname(file.originalname));

            
            // file.fieldname is name of the field (image)
            // path.extname get the uploaded file extension
    }
});

Multer Storage middleware

const upload = multer({storage:storage}).single('image');

Post Router 

app.post("/compose", upload,(req,res)=>{
    const post={
        title : req.body.title,
        content : req.body.content,
        image :req.file.filename,
        date : new Date(),
    }
    
    console.log(post.image)

    
    posts.push(post);
  res.redirect("/")
    
} );

Sending the data by getting 

const upload = multer({storage:storage}).single('image');
app.get("/",(req,res)=>{
  
    res.render("home" , {posts:posts} )    
});

Form input name field

<form class="form-control"action="/compose" method="post" 
enctype="multipart/form-data">
   <label for="exampleFormControlinput2" class="form-label">Photo</label>
        <input type="file" class="form-control" name="image" id="exampleFormControlinput2" rows="3"></input>
        <!-- <input type="text" class="form-control" name="image" id="exampleFormControlinput2" rows="3"></input>
           -->

    <button class="btn btn-primary"type="submit">submit</button>
</form>

Form array taking data from post route


         <% posts.forEach( function (post){ %>
          
          <img class="contenr">
            <img src="./uploads/<%= post.image %>" alt="photo"width="200px" height="200px" alt="photu"></img> 
            <h1><%=post.title %> </h1>
            <h4><%=post.date %> </h4>
            <p><%=post.content%></p>
            </div>
           
        <% }) %>

Comments

Post a Comment