如何获得multipart/form-data?

How to get multipart/form-data?

当我将表单提交到 提交表单按钮 时,一切正常,上传的文件已登录到服务器控制台,但为什么 Multipart:当我点击 使用 fetch

提交时,未找到边界 错误
const express = require("express");
var bodyParser = require("body-parser");
const app = express();
const multer = require("multer");

const fileStorageEngine = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "./images");
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + "--" + file.originalname);
  },
});

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

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.text());

app.get("/", (req, res) => {
  res.send(`
  <form action="/push" method="POST" enctype="multipart/form-data">
  <input type="file" name="image" />
  <button type="submit">Submit form</button>
  <button onclick="send(event)" type="submit">Submit using fetch</button>
</form>

<script>
  function send(event) {
    event.preventDefault();
    let formData = new FormData(event.currentTarget.parentElement);
    fetch("/push", {
      body: formData,
      headers: {
      "Content-Type": "multipart/form-data",
      },
      method: "POST",
    }).then((data) => console.log(data));
  }
</script>
`);
});

app.post("/push", upload.single("image"), (req, res) => {
  console.log(req.file);
});

app.listen(3000);

我想你想上传一张图片?为此,您需要在获取请求 uri 中传递三个参数,在表单数据中输入类型和名称。例如:

fetch("/push", {
      body: {uri :formData.uri ,
             type: formData.type,
             name: forData.name}
         headers: {
        "Content-Type": "multipart/form-data",
        },
        method: "POST",
      }).then((data) => console.log(data));
     }