Multer给req.file undefined

时间:2016-07-29 05:03:31

标签: javascript jquery html node.js multer

我正在尝试使用multer上传文件。这是代码:

HTML

<form action="/" method="post" encrypt="multipart/form-data" >
      <input  name="upl"  type="file" ></br>
      <input  type="text" name="onenee" ></br>
      <input type="submit" value="submit" />

</form>

NODE JS

var express = require('express');
// var csrf = require('csurf');
var passport = require('passport');
var Product = require('../models/product');
var multer  = require('multer');
var upload = multer({ dest: 'public/uploads/' });

var router = express.Router();

router.post('/', upload.single('upl'), function (req, res, next) {
        console.log(' Field name1 '+ req.body.onenee);
        console.log(' Field name2 '+ req.files);
        console.log(' Field name3 '+ req.file);
        res.send(req.file);
});

我从控制台获得的输出

  

字段名称1 hi

     

字段名称2未定义

     

字段名称3未定义

     

POST / 200 15.536 ms - -

2 个答案:

答案 0 :(得分:3)

您的表单属性不正确,请将encrypt更改为enctype。 您的文件将通过req.file

提供

更新:
使用扩展名重命名文件:

var storage = multer.diskStorage({
        destination: function(req, file, cb) {
            cb(null, './public/uploads/'); // Make sure this folder exists
        },
        filename: function(req, file, cb) {
            var ext = file.originalname.split('.').pop();
            cb(null, file.fieldname + '-' + Date.now() + '.' + ext);
        }
    }),
    upload = multer({ storage: storage }).single('upl');

router.post('/', upload, function (req, res, next) {
        console.log('body', req.body);
        console.log('file', req.file);
});

答案 1 :(得分:0)

Do not use:

cb(null, file.fieldname + '-' + Date.now() + '.' + ext);

Instead of use this below code

cb(null, Date.now() + '.jpg');