有人知道为什么 req.file 返回 undefined 吗?

问题描述 投票:0回答:1

有人知道为什么 req.file 返回 undefined 吗?我确定我使用了一个图像文件,我知道为什么但 multer 一直对我这样做


const multer = require('multer');
const upload = multer({ storage: multer.memoryStorage() });

app.post("/sign-up", upload.single("icon"), async (req, res) => {
  let html = req.body.data;
  console.log(html);
  if (html.dp !== process.env.devPassword)
    return res.status(400).json({ error: `Incorrect password!` });

  if (!req.file)
    return res.status(400).json({ error: `Please upload an image.` });

  let image = req.file
console.log(image)
  let date = new Date();
  let newdate =
    date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();

  let data = await profileShema.find().sort({ username: 1 });

  if (data.find((v) => v.username === html.uname.replace(/</g, "&lt;")))
    return res.status(400).json({ error: `That username is already taken.` });

  let newProfile = new profileShema({
    username: html.uname.replace(/</g, "&lt;"),
    password: html.psw.replace(/</g, "&lt;"),
    icon: image.buffer,
    date: `${newdate}`,
    followers: 0,
    discord: null,
    twitter: null,
    author: false,
  }).save();

  return res
    .status(200)
    .json({ success: `${html.uname.replace(/</g, "&lt;")} added!` });
});
 <form class="modal-content animate" id="FormSignUp" action="/sign-up" method="post" enctype="multipart/form-data">
            <div class="container">
                <label for="icon"><b>Avatar</b></label>
                <input type="file" id="icon" name="icon" accept=".jpg, .jpeg, .png" required />
                <label for="uname"><b>Username</b></label>
                <input type="text" placeholder="Enter Username" name="uname" autocomplete="off" required />
                <label for="psw"><b>Password</b></label>
                <input type="password" placeholder="Enter Password" name="psw" required />
                <label for="dp"><b>Developer Password</b></label>
                <input type="password" placeholder="Enter Developer Password" name="dp" required />
            </div>
            <div class="container">
                <button type="submit" class="submitbtn">Sign Up</button>
            </div>
        </form>
        
<script>
        const form = document.getElementById("FormSignUp");
        const error = document.getElementById("error");
        const success = document.getElementById("success");

        form.addEventListener("submit", async (e) => {
            e.preventDefault();
            const data = Object.fromEntries(new FormData(form).entries());
            console.log(data)
            const response = await fetch("/sign-up", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ data }),
            });

            if (response.ok) {
                // Display success message here
                const successData = await response.json();
                success.innerHTML = `<span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
            <strong>Success!</strong> ${successData.success}`;
                success.style.display = "block";
            } else {
                const errorData = await response.json();
                error.innerHTML = `<span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
        ${errorData.error}`;
                error.style.display = "block";
            }
        });
    </script>

当我尝试上传文件时,它总是返回 undefined 我不确定为什么,我尝试搜索答案但找不到任何东西,而且我正在使用 GitHub,所以这就是我不使用 /uploads 的原因

javascript html node.js multer
1个回答
0
投票

您需要发送一个表单数据实例对象,而不是一个普通对象,这就是它现在失败的原因。

因此,在序列化表单后,将每个属性附加到表单数据。

试试这个:

const formData = new FormData();

for (const key in data) {
    formData.append(key, data[key]);
}


const response = await fetch("/sign-up", {
    method: "POST",
    body: formData
});
© www.soinside.com 2019 - 2024. All rights reserved.