将文件路径复制到multer中的其他变量

时间:2016-09-21 15:27:11

标签: node.js

var multer  = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname+ '-' + Date.now()+'.jpg')
    }
});
var upload = multer({ storage:   storage });

app.post('/multer', upload.single('file'));

我希望在点击文件的api路径之后或者我们可以说上面代码中写的文件名应该显示在console.log中

1 个答案:

答案 0 :(得分:0)

为什么不:

var multer  = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
           cb(null, './uploads/')
  },
  filename: function (req, file, cb) {
    var fileName = file.originalname+ '-' + Date.now()+'.jpg';
    console.log(fileName);
    cb(null, fileName);
    }
   });
var upload = multer({ storage:   storage });

app.post('/multer', upload.single('file'));

编辑:对于稍后使用的信息,最好的方法是向app.post添加其他中间件,例如:

app.post('/multer', upload.single('file'), function(req, res) {
    console.log(req.body); // form fields
    /* example output:
    { title: 'abc' }
     */
    console.log(req.file); // form files
    /* example output:
            { fieldname: 'upl',
              originalname: 'grumpy.png',
              encoding: '7bit',
              mimetype: 'image/png',
              destination: './uploads/',
              filename: '436ec561793aa4dc475a88e84776b1b9',
              path: 'uploads/436ec561793aa4dc475a88e84776b1b9',
              size: 277056 }
     */
    res.status(204).end();
});

console.log(req.file);替换为您的mongodb电话。