req.file是未定义的multer

时间:2016-09-18 06:25:59

标签: javascript node.js express multer

这让我发疯了。我试图搜索,但提供的所有解决方案都无法正常工作。 我正在尝试使用multer创建一个简单的文件上传,但似乎无法使其工作,因为req.file似乎总是未定义。

有什么想法吗?完全难倒......没有任何工作,它只是回归未定义!

app.js

Sub Calculate
    With Calculations
        hours = .Range("E2").Value
        If hours <= 8 Then
            .Range("A2").Value = hours
            .Range("B2").Value = 0
            .Range("C2").Value = 0
        ElseIf hours <= 12 Then
            .Range("A2").Value = 8
            .Range("B2").Value = hours - 8
            .Range("C2").Value = 0
        Else
            .Range("A2").Value = 8
            .Range("B2").Value = 4
            .Range("C2").Value = hours - 12
        End If
    End With
End Sub

这是我的HTML:

var path = require('path'),
routes = require('./routes'),
exphbs = require('express-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
moment = require('moment');


module.exports = function(app) {

  app.use(morgan('dev'));
  app.use(bodyParser.urlencoded({'extended':true}));
  app.use(bodyParser.json());
  //app.use(multer({ dest: path.join(__dirname, 'public/upload/temp')}));
  app.use(methodOverride());
  app.use(cookieParser('some-secret-value-here'));
  routes(app);//moving the routes to routes folder.

  app.use('/public/', express.static(path.join(__dirname,'../public')));
  if ('development' === app.get('env')) {
    app.use(errorHandler());
  }

  app.engine('handlebars', exphbs.create({
      defaultLayout: 'main',
      layoutsDir: app.get('views') + '/layouts',
      partialsDir: [app.get('views') + '/partials'],
      helpers: {
                timeago: function(timestamp) {
                          return     moment(timestamp).startOf('minute').fromNow();
                }
              }
  }).engine);
  app.set('view engine', 'handlebars');
      return app;
};

路线:

  <form method="post" action="/images" enctype="multipart/form-data">
<div class="panel-body form-horizontal">
  <div class="form-group col-md-12">
    <label class="col-sm-2 control-label" for="file">Browse:</label>
    <div class="col-md-10">
      <input class="form-control" type="file" name="file" id="file">
    </div>
  </div>

  <div class="form-group col-md-12">
    <label class="col-md-2 control-label" for="title">Title:</label>
    <div class="col-md-10">
      <input class="form-control" type="text" name="title">
    </div>
  </div>

  <div class="form-group col-md-12">
      <label class="col-md-2 control-label" for="description">Description:</label>
      <div class="col-md-10">
        <textarea class="form-control" name="description" rows="2"></textarea>
      </div>
    </div>

    <div class="form-group col-md-12">
        <div class="col-md-12 text-right">
          <button type="submit" id="login-btn" class="btn btn-success" type="button">
            <i class="fa fa-cloud-upload "></i> Upload Image</button>
        </div>
    </div>
  </div>
</form>

控制器:

var express = require('express'),
path = require('path'),
router = express.Router(),
home = require('../controllers/home'),
image = require('../controllers/image'),
multer = require('multer');

var upload = multer({ dest: path.join(__dirname, 'public/upload/temp')});


module.exports = function(app) {
  router.get('/', home.index);
  router.get('/images/:image_id',  image.index);
  router.post('/images', upload.single('file'), image.create);
  router.post('/images/:image_id/like', image.like);
  router.post('/images/:image_id/comment', image.comment);
  app.use(router);
};

再说一遍...... Req.body完全是空的......我认为它是:     body {}

我想我已经取得了一些进展。我看到文件和正文的东西,但它仍然说它是未定义的?      body:{title:'fdsfdsa',描述:'fdsafdsa'},      originalMethod:'POST',      秘密:'某些秘密价值 - 这里',      饼干: {},      signedCookies:{},      路线:       路线{         路径:'/ images',         stack:[[Object],[Object]],         方法:{post:true}},      阅读:[功能],      文件:       {fieldname:'file',         originalname:'Chrysanthemum2.jpg',         编码:'7bit',         mimetype:'image / jpeg',         destination:'C:\ testapp \ server \ public \ upload \ temp',         文件名:'fd17765e4cd03268db6757b8cfb21649',         路径:'C:\ testapp \ server \ public \ upload \ temp \ fd17765e4cd03268db6757b8c       b21649' ,         大小:15973}} ypeError:无法读取未定义的属性“文件”

1 个答案:

答案 0 :(得分:1)

如果您使用的是upload.single()(代码显示的代码),则结果将显示在req.file中,而不是req.files中。所以改变这个:

create: function(req, res) {        
    console.log(req.files);
}

到此:

create: function(req, res) {        
    console.log(req.file);
}

此外,如果您希望使用此路线:

router.post('/images', image.create);

然后,您没有为该路由安装upload()中间件。