NodeJS 如何修复Multer中间件时,它无法创建上传文件夹和更改文件名?

wz8daaqr  于 2023-06-05  发布在  Node.js
关注(0)|答案(2)|浏览(219)

我正在尝试使用nodejs和multer上传pdf到服务器,但有一个问题。a从ejs模板发送一个文件,它必须保存在磁盘上名为上传的文件夹中,文件名更改为特定名称。但是Multer中间件不工作,没有创建文件夹,没有更改文件名,这是怎么回事
有部分代码。
ejs文件

<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>

中间件:

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);

邮政职能

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" });
  }
};
prdp8dxp

prdp8dxp1#

发送文件时,必须以表单的形式发送,信息来自req.file,而不是req.body

uoifb46i

uoifb46i2#

要上传文件,您需要提交multipart/form-data请求,而不是JSON,您可以使用FormData
您可以轻松地从HTML表单构造FormData有效负载,然后在服务器上从req.file读取pdf,而不是body。(您可以使用req.file.filename添加文件名)。
试试这个(你需要添加name属性,它将对应于服务器上req.body的属性):
HTML:

<form enctype="multipart/form-data">
        <input type="text" placeholder="Book Name" id="name" name="name" />
        <input type="text" placeholder="Author " id="author" name="author" />
        <input type="text" placeholder="Buy link" id="link" name="link" />
        <input type="text" placeholder="Book description" id="desc" name="desc" />
        <input type="file" name="pdf" id="pdf" placeholder="upload file" />
        <button type="submit">Add</button>
      </form>
<script>

      let form = document.querySelector("form");

      form.addEventListener("submit", async (e) => {

        e.preventDefault();

        const formData = new FormData(form);

        console.log('form fields: ',  Object.fromEntries(formData.entries()));

        try {
          const res = await fetch("/addBooks", {
            method: "POST",
            body: formData
          });
          console.log('ok', res);
         } catch(err) {
            console.log(err);
         }
        });

</script>

服务器:

let addBook = async (req, res) => {
  
  console.log("reqbody >> ", req.body);

  let { name, author, desc, link} = req.body;

  let pdf = req.file.filename;

  console.log( name, author, desc, link, pdf);

  try {
    let _book = await books.create({
      name,
      author,
      description: desc,
      buyLink: link,
      pdf
    });
    if (_book) {
      res.status(200).send({ msg: "success" });
    }
  } catch (error) {
    logger.error("system crashed try again ");
    res.status(400).send({ msg: "Wrong" });
  }
};

相关问题