如何解决Multer错误:表格的意外结束?
我发现了有关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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
嘿 @sreca ,今天刚刚面对这个问题,希望我能在这里和任何人阅读此书。
解决关于
意外的表单
意外的问题的意外结束的意外结束,您在将
content-type-type
作为解决方案方面是正确的。这是因为使用常规获取或XMLHTTPRequest发送formdata()
将自动由浏览器设置标头。浏览器还将在所有boundare
中连接所有Multipart/form-data
请求中所需的,以指示何时开始和结束表单。有关更多详细信息,请参见有关使用formdata对象 ...明确设置content-type
有警告。现在缺少文件的潜在修复程序
,关于丢失的文件,它可能对您期望的路径有不正确的参考。我不使用
diskstorage
,但是我使用的是常规dest
选项来保存我的文件并遇到了相同的问题(想要将图像保存到./ andsets/images
)。 对我有用的是提供完整的目录路径。也许在目标属性中更改您的回调功能将解决问题。希望这有帮助!
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 theContent-Type
as a solution. This is because sendingFormData()
with regular Fetch or XMLHttpRequest will automatically have the header set by the Browser. The Browser will also attach theboundary
needed in allmultipart/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 settingContent-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 regulardest
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 towill solve the issue. Hope this helps!
就我而言,这个问题神奇地降低了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
我也是因为我在同一路线上使用了多个中间件,所以我使用了全局中间件,然后在子路由中应用了另一个中间件。因此,这引起了混合。
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.