Node.js multer保存文件后修改req.body

Node.js multer保存文件后修改req.body,node.js,express,multer,Node.js,Express,Multer,我想不出一件简单的事。如果我通过请求传递文件,我想保存它们,然后在同一个multer中间件中稍微修改req.body。我的multer中间件: const storage=multer.diskStorage({ 目的地:(请求、文件、cb)=>{ cb(空“./上传/”) }, 文件名:(请求、文件、cb)=>{ cb(null,请求主体。\u id+path.extname(file.originalname)) }, }) const fileFilter=(请求,文件:Express.M

我想不出一件简单的事。如果我通过请求传递文件,我想保存它们,然后在同一个multer中间件中稍微修改req.body。我的multer中间件:

const storage=multer.diskStorage({
目的地:(请求、文件、cb)=>{
cb(空“./上传/”)
},
文件名:(请求、文件、cb)=>{
cb(null,请求主体。\u id+path.extname(file.originalname))
},
})
const fileFilter=(请求,文件:Express.Multer.file,cb:Multer.FileFilterCallback)=>{
如果(
file.mimetype==='audio/wave'||
file.mimetype==='image/png'||
file.mimetype==='image/jpeg'
)
返回cb(null,true)
cb(空,假)
}
const upload=multer({
存储:存储,
限制:{
文件大小:1024*1024*3,//最多3兆字节
},
fileFilter:fileFilter,
})
export const saveFiles=upload.fields([
{name:'audio',最大计数:1},
{name:'image',最大计数:1},
])
现在,我在路由器中执行此操作:

if(请求文件){
if((如有).files.audio请求)
req.body.data.audio=(req为任意).files.audio[0].path.replace(“\\\”,“/”)
if((请求为任意).files.image)
req.body.data.image=(req为任意).files.image[0].path.replace(“\\\”,“/”)
}

这有点烦人,我想在multer启动下一个()之前,在multer内部进行操作。我就是不知道怎么做。

所以,
saveFiles
是您的中间件功能。您没有显示实际使用它的位置,但可能您正在路由器中将它注册为某个中间件。因为它是中间件,这意味着它是一个期望使用参数
(req,res,next)
调用的函数。您可以用自己的
参数替换下一个
参数,并按如下方式进行工作:

// multer's middlware function, we will wrap
const saveFilesMiddleware = upload.fields([
    { name: 'audio', maxCount: 1 },
    { name: 'image', maxCount: 1 },
]);

// wrap the multer middleware with our own
export const saveFiles = function(req, res, next) {
     saveFilesMiddleware(req, res, err => {
         if (err) {
             // upon error, just call the real next with the error
             next(err);
         } else {
             // when no error, do our housekeeping in req.body
             if (req.files) {
                if ((req as any).files.audio)
                     req.body.data.audio = (req as any).files.audio[0].path.replace('\\', '/');
                if ((req as any).files.image)
                     req.body.data.image = (req as any).files.image[0].path.replace('\\', '/');
             }
             next();
         }
     });        
};

对代码进行了更正-它没有在您的
req.body
代码之后调用
next()
。谢谢。在发布了这个问题之后,我突然想到了这个确切的想法。我想在发布之前我应该想得更多,但我真的很感激。@irondsd-对于multer提供的所有用于定制其功能的钩子,它总是让我惊讶,它没有提供bulit-in钩子来知道何时完成。我想这就是你必须要做的。