Search code examples
node.jsmulter-s3

How to get req.body parameters in multer s3


var upload = multer({
storage: multerS3({
    s3: s3,
    bucket: 'bucket',
    metadata: function(req, file, cb) {
        cb(null, {
            fieldName: file.fieldname
        });
    },
    key: function(req, file, cb) {
        console.log('req.body', req.params.id); //not getting
        console.log('req.body', req.body);
        //Not getting param here that passed in api 
        //Need to save file on s3 at specific location i.e /foldername/filename
        //But the folder name not getting from API
        cb(null, file.originalname)
    }
})  }).array('userFile', 1);

Above is multer s3 code

app.post('/saveData', function(req, res, next) {
upload(req, res, function(err) {
    console.log('err' + err);
    var status = '';
    var result = '';
    var link = '';
    if (err) {
        status = false;
    } else {
        status = true;
    }
    result = {
        "status": status,
        "link": link
    }
});
res.send(result);   });

Above code where calling multer upload function. I am parsing data in API (from Angular2, set -Content-Type": "multipart/form-data) as formdata

let formData: FormData = new FormData();
formData.append('userFile', file);
formData.append('fileName', fileName);

I require the req.body data from API like folder name and other, so I can put the file to specific place on S3. Need req.body data inside the key: function(req, file, cb) { of multerS3.


Solution

  • It seems to be a bug in multer, but as said here you can reorder the parameters when sending.

    https://github.com/expressjs/multer/issues/322#issuecomment-191642374