如何解决Multer错误:表格的意外结束?

发布于 2025-02-13 08:37:30 字数 2234 浏览 0 评论 0原文

我发现了有关Multer的其他类似问题,但没有答案。我正在尝试使用Next.js(前端)和node.js(后端)上传文件。使用开发工具时,数据将通过网络选项卡发布。

以下是我的设置:

app.js

const express = require('express');
const bodyParser = require('body-parser');

// Get routes
const routeUser = require('./routes/user');

// Create an express server
var app = express();

// Add necessary middleware
app.use(bodyParser.urlencoded({ extended: true })); // Support encoded bodies
app.use(bodyParser.json({
  type: ["application/x-www-form-urlencoded", "application/json"], // Support json encoded bodies
}));

// Custom routes
routeUser(app);

// Start server on port 1234
app.listen(1234, () => {
  console.log("API is running.");
});

路线/user.js

const multer = require('multer');

module.exports = function(app) {

  const upload = multer({
    storage: multer.diskStorage({
      destination: (req, file, cb) => {
        cb(null, "./user_photos");
      },
      filename: (req, file, cb) => {
        cb(null, file.originalname)
      }
    })
  });

  app.post('/user/update', upload.single('user_photo'), (req, res) => {

    console.log(req.body, req.file);

  });
}

form

submit(event) {
  event.preventDefault();
  let form_values = new FormData(event.target);
  fetch(this.props.env.api + "/user/update", {
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data; boundary=MyBoundary',
    },
    body: form_values
  }).then((response) => {
    return response.json();
  }).then((response) => {
    console.log(response);
  });
}

------

<form onSubmit={this.submit}>
  <input type="file" name="user_photo"/>
  <button type="submit">Upload</button>
</form>

我尝试了几个教程,我正在根据文档,但是我一直会收到以下错误:

Error: Unexpected end of form
    at Multipart._final (...\node_modules\busboy\lib\types\multipart.js:588:17)

如果我将multipart/form-data作为content-type ,则表单没有任何问题,但没有文件。我的猜测这与formdata对象的方式有关。

I found other similar questions regarding Multer, but with no answers. I'm trying to upload a file with next.js (front-end) and node.js (back-end). The data is being posted via the network tab when using dev tools.

Below is my setup:

app.js

const express = require('express');
const bodyParser = require('body-parser');

// Get routes
const routeUser = require('./routes/user');

// Create an express server
var app = express();

// Add necessary middleware
app.use(bodyParser.urlencoded({ extended: true })); // Support encoded bodies
app.use(bodyParser.json({
  type: ["application/x-www-form-urlencoded", "application/json"], // Support json encoded bodies
}));

// Custom routes
routeUser(app);

// Start server on port 1234
app.listen(1234, () => {
  console.log("API is running.");
});

route/user.js

const multer = require('multer');

module.exports = function(app) {

  const upload = multer({
    storage: multer.diskStorage({
      destination: (req, file, cb) => {
        cb(null, "./user_photos");
      },
      filename: (req, file, cb) => {
        cb(null, file.originalname)
      }
    })
  });

  app.post('/user/update', upload.single('user_photo'), (req, res) => {

    console.log(req.body, req.file);

  });
}

Form

submit(event) {
  event.preventDefault();
  let form_values = new FormData(event.target);
  fetch(this.props.env.api + "/user/update", {
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data; boundary=MyBoundary',
    },
    body: form_values
  }).then((response) => {
    return response.json();
  }).then((response) => {
    console.log(response);
  });
}

------

<form onSubmit={this.submit}>
  <input type="file" name="user_photo"/>
  <button type="submit">Upload</button>
</form>

I've tried several tutorials, I'm setting it up according to the docs, yet I keep getting the following error:

Error: Unexpected end of form
    at Multipart._final (...\node_modules\busboy\lib\types\multipart.js:588:17)

If I remove multipart/form-data as Content-Type, the form submits with no problem, but with no file. My guess it has something to do with the way the formData object is being received.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

嘿看小鸭子会跑 2025-02-20 08:37:30

@sreca ,今天刚刚面对这个问题,希望我能在这里和任何人阅读此书。

解决关于意外的表单

意外的问题的意外结束的意外结束,您在将content-type-type作为解决方案方面是正确的。这是因为使用常规获取或XMLHTTPRequest发送formdata()将自动由浏览器设置标头。浏览器还将在所有boundare中连接所有Multipart/form-data请求中所需的,以指示何时开始和结束表单。有关更多详细信息,请参见有关使用formdata对象 ...明确设置content-type有警告。

现在缺少文件的潜在修复程序

,关于丢失的文件,它可能对您期望的路径有不正确的参考。我不使用diskstorage,但是我使用的是常规dest选项来保存我的文件并遇到了相同的问题(想要将图像保存到./ andsets/images)。 对我有用的是提供完整的目录路径。也许在目标属性中更改您的回调功能

// Assuming the the path module is 'required' or 'imported' beforehand
cb(null, path.resolve(__dirname, '<path-to-desired-folder>'));

将解决问题。希望这有帮助!

Hey @SReca, just faced this issue today and hope I can help you out here and anybody else reading this.

Resolving Unexpected end of form

Regarding the original issue about Unexpected end of form, you are correct in removing the Content-Type as a solution. This is because sending FormData() with regular Fetch or XMLHttpRequest will automatically have the header set by the Browser. The Browser will also attach the boundary needed in all multipart/form-data requests in order indicate when a form starts and ends. More details can be found on MDN's docs about Using FormData Objects... there's a warning about explicitly setting Content-Type.

Potential fix for missing file

Now, about the missing file, it's possible that it has an incorrect reference to the path you're expecting. I am not using diskStorage, but I am using regular dest option to save my file and had the same problem (wanted to save images to ./assets/images). What worked for me was to supply the complete directory path. Maybe changing your callback function in the destination property to

// Assuming the the path module is 'required' or 'imported' beforehand
cb(null, path.resolve(__dirname, '<path-to-desired-folder>'));

will solve the issue. Hope this helps!

天冷不及心凉 2025-02-20 08:37:30

就我而言,这个问题神奇地降低了Multer至1.4.3。

请参阅 https://github.com/expressjs/multer/multer/multer/issues/1144

In my case the problem magically went away by downgrading Multer to 1.4.3.

See https://github.com/expressjs/multer/issues/1144

如梦初醒的夏天 2025-02-20 08:37:30

我也是因为我在同一路线上使用了多个中间件,所以我使用了全局中间件,然后在子路由中应用了另一个中间件。因此,这引起了混合。

What caused this too me was because I was using multiple middleware on the same route, I was using global middleware and then applied another middleware in sub route. so this caused conflits.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文