How to disable Express BodyParser for file uploads (Node.js)

后端 未结 7 1883
深忆病人
深忆病人 2020-11-30 18:26

This seems like it should be a fairly simple question, but I\'m having a really hard time figuring out how to approach it.

I\'m using Node.js + Express to build a we

7条回答
  •  借酒劲吻你
    2020-11-30 19:15

    I've faced similar problems in 3.1.1 and found (not so pretty IMO) solution:

    to disable bodyParser for multipart/form-data:

    var bodyParser = express.bodyParser();
    app.use(function(req,res,next){
        if(req.get('content-type').indexOf('multipart/form-data') === 0)return next();
        bodyParser(req,res,next);
    });
    

    and for parsing the content:

    app.all('/:token?/:collection',function(req,res,next){
        if(req.get('content-type').indexOf('multipart/form-data') !== 0)return next();
        if(req.method != 'POST' && req.method != 'PUT')return next();
        //...use your custom code here
    });
    

    for example I'm using node-multiparty where the custom code should look like this:

        var form = new multiparty.Form();
    
        form.on('file',function(name,file){
           //...per file event handling
        });     
    
        form.parse(req, function(err, fields, files) {
           //...next();
        });
    

提交回复
热议问题