文件被 multer 保存后修改 req.body

Modify req.body after file was saved by multer

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

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './uploads/')
    },
    filename: (req, file, cb) => {
        cb(null, req.body._id + path.extname(file.originalname))
    },
})

const fileFilter = (req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
    if (
        file.mimetype === 'audio/wave' ||
        file.mimetype === 'image/png' ||
        file.mimetype === 'image/jpeg'
    )
        return cb(null, true)

    cb(null, false)
}
const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 3, // up to 3 megabytes
    },
    fileFilter: fileFilter,
})

export const saveFiles = upload.fields([
    { name: 'audio', maxCount: 1 },
    { name: 'image', maxCount: 1 },
])

现在我在路由器上做:

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('\', '/')
    }

这有点烦人,我想在 multer 触发 next() 之前以某种方式在 multer 中执行此操作。我就是想不通。

因此,saveFiles 是您的中间件功能。您没有显示实际使用它的位置,但大概是您将它作为中间件注册在路由器中的某个地方。因为它是中间件,这意味着它是一个预期使用参数 (req, res, next) 调用的函数。您可以将 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();
         }
     });        
};