繁体   English   中英

Node / React:我无法使用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 DB 中,我只想将图像保存在我的图像文件夹中。 我已经验证了路径 (../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() };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM