gpt4 book ai didi

node.js - Multer 未填充 req.body 和 req.file

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:57 29 4
gpt4 key购买 nike

我正在使用 Multer 在 keystone 环境中解析多部分表单,并且无法访问路由 Controller 内的 req.body 和 req.file 数据

路线/index.js

var keystone = require('keystone'),
middleware = require('./middleware');

var bodyParser = require('body-parser');

//multi-part form parser for FTP api
var multer = require('multer');
var storage = multer.memoryStorage();
var upload = multer({storage: storage});

exports = module.exports = function(app) {
app.use(bodyParser.json({limit: '10mb'}));
app.use(bodyParser.urlencoded({limit: '10mb', extended: true}));
app.post('/upload_api', upload.single('formFile'), routes.api.uploadFTP);
};

路由/api/uploadFTP.js

var keystone = require('keystone');
var ftpMod = require('ftp');
var fs = require('fs');

exports = module.exports = function(req, res) {
console.log("req.body is ");
console.log(req.body);
console.log("req.file is ");
console.log(req.file);
res.send("console.log() outputted to screen");
}

public/test-upload.html

<html>
<body>
<form name="sampleForm" enctype="multipart/form-data" action="/upload_api" method="post">
<p>Method</p>
<input type="text" name="method"><br>
<p>Options</p>
<input type="text" name="options"><br>
<p>File</p>
<input type="file" name="formFile"><br><br>
<input type="submit" value="Click to Send">
</form>
</body>
</html>

我从nodejs收到的响应是

>req.body is 
{}
req.file is
undefined

我期待 req.body 包含 {method: "sometext"}和要填充的 req.file

最佳答案

您无法获取 req.bodyreq.file 中的值。将 uploadFTP.js 替换为下面给出的代码。

var multer = require('multer');
var path = require('path');

var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, <<path where you want to store your files>>);
},
filename: function(req, file, callback) {
callback(null, path.basename(Date.now() + '_' + file.originalname));
},
});
var maxSize = 1024 * 1024;
var upload = multer({
storage: storage,
fileFilter: function(req, file, callback) {
var ext = path.extname(file.originalname);
if(ext !== '.gif' && ext !== '.jpeg') {
return callback(res.status(202).end();, null);
}
callback(null, true);
},
limits: {fileSize: maxSize},
}).single('image');

exports = module.exports = function (req, res) {

upload(req, res, function(err) {
console.log(storage.diskStorage);
if(err) {
return res.status(201).end();
}
//Do stuff here
res.status(200).end();
});
}

替换index.js中的以下行

app.post('/upload_api', upload.single('formFile'), routes.api.uploadFTP);

app.post('/upload_api', routes.api.uploadFTP);

关于node.js - Multer 未填充 req.body 和 req.file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44679064/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com