我们应该使用 api 将图像或文件作为 blob 从前端发送到后端,还是可以使用 formData? [关闭]

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

不太明白blob是什么。在 Node.js 端为 MySQL 数据库保存图像的最佳方法是什么?还有我应该如何将这个文件发送到后端

让我告诉你我是怎么做到的。如果你能告诉我我这样做是否正确,我将不胜感激。

React.js

const handleSubmit = async (e) => {
    e.preventDefault();
    const data = new FormData();
    for (let i = 0; i < files.length; i++) {
      data.append("imgs", files[i][0]);
    }
    data.append("title", text);
    data.append("content", content);

    try {
      const res = await fetch("http://localhost:3001/admin/create-blog", {
        method: "POST",
        body: data,
        headers: { XAuthToken: `${something} ${token}` },
      });
      const dataMsg = res.json();

      if (dataMsg) {
        setText("");
        setContent("");
        setFiles([]);
        navigate({
          pathname: "/Admin-Panel",
          search: "succes=true"
        }, { preventScrollReset: true, replace: true });
      }

    } catch (err) {
      console.log(err);
    }
  };

** Node.js**

router.post(
  "/create-blog",
  isAuth,
  imgUplaod.upload.array("imgs"),
  async (req, res) => {
    const title = req.body.title;
    const content = req.body.content;
    const image = req.files;

    try {
      const blog = await Blog.create({
        title: title,
        url: slugField(title),
        content: content,
      });

      for (let i = 0; i < req.files.length; i++) {
        const image = await Image.create({ name: req.files[i].filename });

        await blog.addImages(image);
      }

      res.json({ isOk: "ok" });
    } catch (err) {
      console.log("err: ", err);
      res.status(500).send(err);
    }
  }
);
mysql node.js reactjs sequelize.js blob
© www.soinside.com 2019 - 2024. All rights reserved.