multer访问req.body而不上传文件 [英] Multer access req.body without uploading files
问题描述
我有一个带有一些文本字段和文件输入的表格,不能为空,我想先对文本字段进行一些操作(添加到数据库中),如果这些操作成功,则上传文件.这是我现在的代码:
I have a form with some text fields and file inputs which cannot be empty, I want to do some operations with the text fields first(adding to database) and if these operations were successful then upload the files. This is my code right now :
var multer = require('multer');
var getFields = multer();
router.post('/add',getFields.array(),function(req,res){
var artist = new ArtistModel({
name : req.body.name.toLowerCase(),
description:req.body.description,
});
然后我将歌手添加到我的数据库,并在成功的回调中希望文件上传.但是问题是我不能简单地使用getFields.array(),因为我有文件输入,并且收到意外字段"错误,如果我不使用.array(),我将无法获得邮寄请求正文.无论如何,是否首先要获取带有enctype ="multipart/form-data"的表单文本字段,然后再上传文件?
I then add artist to my DB and in the successful callback I want the files to be uploaded. The problem is however I can't simply use getFields.array() because I have file inputs and I get "Unexpected fields" error, and if I dont use .array() I wont be able to get the post request body. Is there anyway to get the form text fields with enctype="multipart/form-data" first and then upload the files?
更新#2 多亏了 Dave ,我能够在不上传文件的情况下获得文本字段,因此我成功地将艺术家添加到数据库中,但是之后不知道如何上传文件, 我在addToDb的回调函数中创建了一个新变量:
Update #2 Thanks to Dave I was able to get the text fields without uploading files , I successfully added my artist to my database, however I couldn't figure out how to upload the files afterwards, I created a new variable in the callback function of my addToDb :
var storage = multer.diskStorage({
destination: function (req, file, cb) {
//cb(null, 'artistsMedia/drake/songs')
var dir = 'artistsMedia/' + req.body.name.toLowerCase()+ '/images';
mkdirp(dir,err => cb(err,dir))
},
filename: function (req, file, cb) {
cb(null, req.body.name.toLowerCase() +'-'+ file.fieldname +'-'+ Date.now() + path.extname(file.originalname)) //Appending extension
},
});
var upload = multer({
storage: storage,
limits :{fileSize :52428800}
}).fields([{name:'Logo',maxCount:1},{name:'artistHome',maxCount:1},{name:'otherImgs',maxCount:10}]);
但是调用upload(req,res,err)
似乎无效.
推荐答案
尝试使用multer的any()
函数:
Try with multer's any()
function:
var multer = require('multer');
var getFields = multer();
router.post('/add',getFields.any(),function(req,res){
// any files, if sent, will be in req.files
var artist = new ArtistModel({
name : req.body.name.toLowerCase(),
description:req.body.description,
});
});
如果确定没有文件提交,请使用multer的none()
函数:
If you are sure there will be no files submitted, use multer's none()
function:
var multer = require('multer');
var getFields = multer();
router.post('/add',getFields.none(),function(req,res){
// uploading files will cause an error
var artist = new ArtistModel({
name : req.body.name.toLowerCase(),
description:req.body.description,
});
});
这篇关于multer访问req.body而不上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!