Search code examples
node.jsexpressmulter

How to fix Multer middleware when it fails to create upload folder and change filename?


i am trying to upload pdf to server using nodejs and multer but there is a problem. a send a file from ejs templet and it must be saved at disk on folder named upload and file name changed to specific name . but what happen that Multer middleware does not work no folder created no filename changed

There are parts of code .

ejs file

 <form enctype="multipart/form-data">
        <input type="text" placeholder="Book Name" id="name" />
        <input type="text" placeholder="Author " id="author" />
        <input type="text" placeholder="Buy link" id="link" />
        <input type="text" placeholder="Book description" id="desc" />
        <input type="file" name="pdf" id="pdf" placeholder="upload file" />
        <button type="submit">Add</button>
      </form>
<script>
      // const multer = import("multer");
      // const upload = multer({ dest: "./public/data/uploads/" });
      let form = document.querySelector("form");
      form.addEventListener("submit", async (e) => {
        let bookName = document.getElementById("name").value;
        let bookAuthor = document.getElementById("author").value;
        let bookLink = document.getElementById("link").value;
        let bookDesc = document.getElementById("desc").value;
        let pdf = document.getElementById("myfile").files[0].name;
        e.preventDefault();
        try {
          const res = await fetch("/addBooks", {
            method: "POST",
            body: JSON.stringify({
              bookName,
              bookAuthor,
              bookDesc,
              bookLink,
              pdf,
            }),
            headers: { "Content-Type": "application/json" },
          });
</script>

middleware:

onst storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "upload");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
    console.log(destination, filename);
  },
});
const upload = multer({ storage });

route.post("/addBooks", upload.single("pdf"), addBook);

post func

let addBook = async (req, res) => {
  console.log("reqbody >> ", req.body);
  let { bookName, bookAuthor, bookDesc, bookLink, pdf } = req.body;
  try {
    let _book = await books.create({
      name: bookName,
      author: bookAuthor,
      description: bookDesc,
      buyLink: bookLink,
      pdf:pdf,
    });
    if (_book) {
      res.status(200).send({ msg: "success" });
    }
  } catch (error) {
    logger.error("system crashed try again ");
    res.status(400).send({ msg: "Wrong" });
  }
};

Solution

  • When sending a file, you must send it in the form, and the information comes in req.file, not in req.body