我发现了有关 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.");
});
路线/用户.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
as Content-Type
,表单提交没有问题,但没有文件。我猜这与方式有关formData
正在接收对象。