NodeJS 当试图将formData转换为express js时,服务器无法识别multipart/form-data

dsekswqp  于 2023-05-06  发布在  Node.js
关注(0)|答案(1)|浏览(151)

我正在尝试将表单数据上传到Express服务器。在我的express js服务器上,我有以下内容:

router.post('/uploads/:id', function(req, res) {
  res.send(req.body);
  const title = req.body.title;
  const file = req.file;
});

我发送回req.body以查看它是否命中了相应的url。当我使用以下命令时:

const response = await fetch('https://example.com/uploads/1234', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(form) });
const responseData = await response.json();

console.log(responseData);

我得到了转换为json的FormData的响应。当我这样运行它时:

const file = fs.createReadStream(`${desktopDir}/ai2html-output/home-pro-Artboard_1.jpg`);
const title = 'My file fsf';

const form = new FormData();
form.append('title', title);
form.append('file', file);

    const response = await fetch('https://example.com/uploads/1234', {
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      body: form });
    const responseData = await response.json();

然后返回一个空对象:{}
我必须在express服务器上设置一些东西才能接收表单数据吗?我需要某种类型的中间件吗?
这里也是我的请求头从服务器响应:

:method: POST
:path: /uploads/1234
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
content-length: 17
content-type: multipart/form-data
origin: file://
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
mwkjh3gx

mwkjh3gx1#

我必须在express服务器上设置一些东西才能接收表单数据吗?
是的,要在 Express 服务器上处理multipart/form-data,您必须配置中间件
例如multer库。

Demo:

服务器.js

const express = require("express");
app = express();
const multer = require("multer");
const upload = multer({ dest: "uploads/" });
//----------------------vvvvvvvvvvvvvvvvvvvvvv <------- middleware
app.post("/uploads/:id", upload.single("file"), function (req, res) {
  const title = req.body.title;
  console.log(req.file);
/*
Output of req.file:
{
  fieldname: 'file',
  originalname: 'test.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: 'uploads/',
  filename: '61d00f21b9813bdcb326082b41b58eb3',
  path: 'uploads\\61d00f21b9813bdcb326082b41b58eb3',
  size: 0
}
*/
  res.json({ msg: `file ${title} uploaded successfully!` });
});
app.listen(1234, () => {
  console.log("app is running on 1234");
});

上传.js

var fs = require("fs");
const fetch = require("node-fetch");
var FormData = require("form-data");

const form = new FormData();
const title = "Test";
const file = fs.createReadStream(`./test.jpg`);
form.append("title", title);
form.append("file", file);

(async () => {
  try {
    const response = await fetch("http://localhost:1234/uploads/1234", {
      method: "POST",
      //   headers: {
      //     "Content-Type": "multipart/form-data",
      //   },
      body: form,
    });
    const responseData = await response.json();
    console.log(responseData); // you got { msg: 'file Test uploaded successfully!' }
  } catch (error) {
    console.error(error);
  }
})();
  • 注意:* Fetch会自动设置header,所以只需带走header "Content-Type": "multipart/form-data"即可。

如果你想将上传的文件保存到一个特定的文件夹“uploads/”中,并且文件的标题带有req.body.title,请将此配置添加到multer中:

const path = require("path");
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/");
  },
  filename: (req, file, cb) => {
    const title = req.body.title;
    cb(null, title + path.extname(file.originalname));
  },
});
const upload = multer({ storage: storage });

相关问题