使用 React 上传文件,nodeJS multer 不起作用

File upload with react, nodeJS multer doesn't work

我制作了这个函数,它从 file 状态获取 file 值(图像)并将其发送到上传路由,通过FormData 对象

  const [file, setFile] = useState(null);
  const submitPost = async (e) => {
  ...
    e.preventDefault();
    if (file) {
      const data = new FormData();
      const fileName = `${Date.now()}${file.name}`;
      data.append("name", fileName);
      data.append("file", file);
      try {
        await fetch("http://localhost:8000/upload", {
          headers: {
            "Content-type": "application/json",
          },
          method: "POST",
          body: JSON.stringify(data),
        });
        // window.location.reload();
      } catch (err) {
        console.log(err);
      }
    }
  };

文件 文件状态中的值来自表单文件输入

        <form className="postOptions" onSubmit={submitPost}>
          <div className="postAreaBot">
            <label htmlFor="file" className="downloadImg">
              <AddAPhotoIcon className="postIcon" />
              <span>Image</span>
            </label>
            <input
              type="file"
              accept=".png,.jpeg,.jpg"
              onChange={(e) => setFile(e.target.files[0])}
              id="file"
              style={{ display: "none" }}
            ></input>
          </div>
          <button type="submit">Post</button>
        </form>

然后将 file 值发送到此路由,以便上传到文件夹 images 内的文件夹 public 使用 multerpath

app.use("/images", express.static(path.join(__dirname, "public/images")));

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "public/images");
  },
  filename: (req, file, cb) => {
    cb(null, req.body.name);
  },
});
const upload = multer({ storage });
app.post("/upload", upload.single("file"), (req, res) => {
  try {
    return res.status(200).json("File uploaded successfully");
  } catch (err) {
    console.log(err);
  }
});

但是图片没有上传

我尝试了什么

我使用 file.originalNamepostman 而不是 file.req.body 并且路由确实有效并且图像正在成功上传,我还检查了值 namefiledata 对象并成功附加它,我看不出问题是什么,为什么它不通过 react fetch 请求上传图像文件?

只需删除 JSON.stringify。并更改您的内容类型,如下例所示:

    await fetch("http://localhost:8000/upload", {
      headers: {
        "Content-type": "multipart/form-data",
      },
      method: "POST",
      body: data,
    });