Parse form value with formidable to filename

后端 未结 2 946
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 11:10

I´m using formidable to handle my file uploads in NodeJs. I´m a little stuck at parsing field values.

How do I get the value of project_id to the form handler, so I can

2条回答
  •  没有蜡笔的小新
    2021-02-06 11:30

    Formidable's end callback doesn't take any parameters, but I'm not sure you even need to call it if you're using the parse callback. I think what you're looking for is something like this:

    var fs = require('fs');
    app.post('/uploads', function(req, res, next) {
        var form = new formidable.IncomingForm();
        form.parse(req, function(err, fields, files) {
            if (err) next(err);
    
            // TODO: make sure my_file and project_id exist    
            fs.rename(files.my_file.path, fields.project_id, function(err) {
                if (err) next(err);
                res.end();
            });
        });
    });
    

    You would need to listen for the end() event if you chose not to use the parse callback, like this:

    new formidable.IncomingForm().parse(req)
        .on('file', function(name, file) {
            console.log('Got file:', name);
        })
        .on('field', function(name, field) {
            console.log('Got a field:', name);
        })
        .on('error', function(err) {
            next(err);
        })
        .on('end', function() {
            res.end();
        });
    

提交回复
热议问题