javascriptnode.jsexpressfile-uploadmulter

Having some issues with uploading images using multer with nodejs express


I am using multer to upload images into a folder in my project. But there is no error showing when using multer and I can't figure out what was the problem. It works perfectly with a basic new project but in my project it is not working

here is the code of the API to upload the image

router.post('/add-product-1', upload.single('image'), (req, res) => {
  console.log(req.body);
  console.log(req.file);
  console.log('llllllllllllllllll');
  res.send('File uploaded!');
});

here req.file is empty, but I was specified the enctype=multipart/form-data

here is the form

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h2>upload images</h2>
 
    <form action="/admin/add-product-1" method="POST" enctype="multipart/form-data">
        <input type="text" name="title">
        <input type="file" name="image">
        <button type="submit">Submit</button>
    </form>
</body>

</html>

and this is the code I used for multer

const multer=require("multer");
const path=require('path')
const storage=multer.diskStorage({
    destination:(req,file,cb)=>{
        cb(null,"Images");
    },
    filename:(req,file,cb)=>{
        console.log(file);
        cb(null,Date.now()+path.extname(file.originalname))
    }
})
const upload=multer({
    storage:storage,
    limits: {
        fileSize: 1024 * 1024 * 5 // 5 MB
      },
    // dest:'Images'
});

module.exports={upload}

And I imported in the api page like

let {upload} = require('../middlewares/multer');

I am looking for what's wrong with this code and still I can't figure out if anyone can correct it. It will be very helpful for me


Solution

  • You need to assign the path for a destination to store the image in diskStorage.

    const storage = multer.diskStorage({
      destination: "./public/uploads",
      filename: (req, file, cb) => {
        cb(null, Date.now() + path.extname(file.originalname));
      },
    });
    

    now the image is stored in public/uploads directory.