Node / React:我无法使用 post 和 multer 上传图片

Node / React : I can't upload an image with my post with multer

我正在尝试创建一个小型社交网络,我们可以在其中发送帖子(带或不带图片)。

我设法创建了没有图片(只有文本)的帖子,效果很好,但是一旦我将图片添加到我的表单并提交表单,就找不到图片了。通常它应该保存在“图像”文件夹中,但它总是空的。

我正在使用 multer 来做到这一点,这是我的代码:

我的表单组件:

const WhatsUpForm = ({ className, id, name, placeholder }) => {
  const [inputValue, setInputValue] = useState("");

  const inputHandler = (e) => {
    setInputValue(e.target.value);
  };

  const submitHandler = async (e) => {
    e.preventDefault();
    const post = {
      author_firstname: JSON.parse(localStorage.getItem("user")).user_firstname,
      author_lastname: JSON.parse(localStorage.getItem("user")).user_lastname,
      message: inputValue,
      date_creation: dayjs().format(),
      image_url: ""
    };

    // POST request
    await POST(ENDPOINTS.CREATE_POST, post);

    // document.location.reload()
  };

  return (
    <form className={className} onSubmit={submitHandler} method="POST" action="/api/post" enctype="multipart/form-data">
      <input className="testt" type="text" id={id} name={name} placeholder={placeholder} required  value={inputValue} onChange={inputHandler}/>
      <div className="icons_container">
        <input type="file" name="image" id="image" className="icons_container__add_file" />
        <label for="image">
          <FontAwesomeIcon icon={faImages} />
        </label>
        <button type="submit" className="icons_container__submit">
          <FontAwesomeIcon icon={faPaperPlane} />
        </button>
      </div>
    </form>
  );
};

我的路线和multer的代码:

const multer = require("multer");
const path = require("path");

const storage = multer.diskStorage({
  destination: (req, file, callback) => {
    callback(null, "../images");
  },
  filename: (req, file, callback) => {
    console.log("multer");
    console.log("file :", file);
    callback(null, Date.now() + path.extname(file.originalname));
  },
});

const upload = multer({ storage: storage });

// Post CRUD
router.get("/", auth, postCtrl.getAllPosts);
router.post("/", auth, upload.single("image"), postCtrl.createPost);
router.delete("/:id", auth, postCtrl.deletePost);

router.put("/:id", auth, postCtrl.updatePost);

console.log("multer") 未触发,当我在浏览器的网络选项卡中查看负载时,我没有看到任何图像。

最后,我的 createPost 函数控制器:

exports.createPost = (req, res, next) => {
  let { body } = req;
  delete(req.body.image_url)
  body = {
    ...body,
    likes: "",
    
  };
  const sql = "INSERT INTO posts SET ?";
  db.query(sql, body, (err, result) => {
    if (err) {
      res.status(404).json({ err });
      throw err;
    }
    res.status(200).json({ msg: "Post added..." });
  });
};

目前,我不想将图像的 URL 放入我的 SQL 数据库中,我只想将图像保存在我的图像文件夹中。我已经验证了路径 (../images) 并且它是正确的。 如何将图片保存到我的图片文件夹中?

我没有看到文件数据从您的 POST 请求发送到服务器。

 // object post doesn't have the file data
  await POST(ENDPOINTS.CREATE_POST, post);

考虑使用 FormData

 const submitHandler = async (e) => {
    e.preventDefault();
    const post = new FormData();
    // non form data
    formData.append("author_firstname", JSON.parse(localStorage.getItem("user")).user_firstname);
    ...
    
    // form data
    formData.append("image",    document.getElementById("image").files[0]);
    ...
    
    // POST request
    await POST(ENDPOINTS.CREATE_POST, post);

    // document.location.reload()
  };