为什么用Multer上传文件在这里不起作用?

时间:2017-02-07 05:34:48

标签: node.js file-upload multer

我尝试在Node.js中使用Multer上传图片。当我在console.log(req.files)时,它给出了undefined。这里有什么问题?

 <form class="form-horizontal" enctype='multipart/form-data' action="/admin/addNewFood" method="post">

        <div class="form-group">
            <label for="image" class="col-sm-2 control-label">Choose Image</label>
            <div class="col-sm-3">
                 <span class="btn btn-default btn-file btn-xs">
                      Browse <input type="file" name="fileUpload">
                 </span>
            </div>

        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="hidden" name="_csrf" value="{{ csrfToken }}">
                <button type="submit" class="btn btn-default">Add</button>
            </div>
        </div>
    </form>

这是我的路线档案

var express = require('express');
var router = express.Router();
var csrf = require('csurf');
var passport = require('passport');
var Cart = require('../Models/cart');
var multer  = require('multer');
var upload = multer({ dest: '../public/uploads/' });
var bodyParser = require('body-parser');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));

router.use(upload.single('fileUpload'));
var csrfProtection = csrf();
router.use(csrfProtection);

router.post('/addNewFood', function (req, res, next) {
    console.log('filesssssssss',req.files);

}

});

我无法弄清楚这里有什么问题。请帮忙

1 个答案:

答案 0 :(得分:0)

我使用这个上传文件,希望这也适合你。

var express = require('express');
    var mongoose = require('mongoose');
    var multer = require('multer');
    var fs = require('fs');
    var Grid = require('gridfs-stream');
    var router = express.Router();
    var upload = multer({dest: 'uploads/'});

    router.post('/upload', upload.any(), function (req, res) {
        var conn = mongoose.connection;
        var Grid = require('gridfs-stream');
        Grid.mongo = mongoose.mongo;
        var path = req.files[0].path
        var path_name = req.files[0].originalname
        var gfs = Grid(conn.db);
        var writestream = gfs.createWriteStream({
            filename: path_name
        });
        fs.createReadStream(path).pipe(writestream);
        writestream.on('close', function (file) {
            fs.unlink(req.files[0].path, function () {
                res.json({id: file._id, message: "success"});
            });
        });

    })