Multer:req.file undefined / empty

时间:2016-03-13 20:10:40

标签: angularjs node.js express file-upload multer

我正在尝试使用Mean Stack上的multer上传图像(表单的一部分)。但是,每个其他数据属性都是发布的,但在图像方面我的定义是不确定的。

HTML

<div class="form-group">
                    <label for="inputEmail1"  class="col-md-2 control-label">Club Logo</label>
                    <div class="col-md-4">
                      <input type="file" id="photo" name="photo" file-model="clubData.file">
                    </div>
               </div>

routes.js

'use strict';


var joinClubTeam = require('../controllers/joinClubTeam.server.controller');
var createClub = require('../controllers/createClub.server.controller');
 // var bodyParser = require('body-parser');

var multer = require('multer');
var upload =  multer({
    dest    : './uploads/',
    onError : function(err, next) {
      console.log('error', err);
      next(err);
    }
  });


module.exports = function (app) {
///////////////////////////////////////////////////////////////////////////////
  /////////////////
  // custom methods
  /////////////////
  app.route('/api/join-club-team')
    .post(joinClubTeam.JoinClubTeam);
///////////////////////////////////////////////////////////////////////////////


app.route('/api/upload', upload.single('photo')).post(createClub.TestFormData);

// 

};

Server Controller.js

use strict';
	/**
	 * Module dependencies
	 */
var path = require('path'),
	mongoose = require('mongoose'),
	Club = mongoose.model('Club'),
	User = mongoose.model('User'),
	Player = mongoose.model('Player'),
	Team = mongoose.model('Team'),
	multer = require('multer'),
	errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
// var upload = multer({dest: './uploads/'});


	exports.TestFormData = function(req, res,next){
		console.log('reaching here');
	console.log(req.body);
	console.log(req.file);
	res.json({success: true});
};

Client Controller.js

'use strict';


angular.module('joinClubTeam').controller('createClubController', ['$scope','$state', '$http', 'Authentication', '$location', 'multipartForm', function($scope, $state, $http, Authentication, location, multipartForm){
	
	        $scope.authentication = Authentication;
	        $scope.clubData ={};
	

	
	$scope.LoadInitialData = function(){

		
		$http.get('api/sports').success(function(response){
			$scope.AllSports = response;
			
			console.log(response);
			$scope.selectedSportId = response[0]._id;
			
		});
		
	};

	
	$scope.submit = function(){

		console.log($scope.clubData.file.name);
		
			// var uploadUrl = '/upload';
		multipartForm.post('/api/upload', $scope.clubData);

	};
	
	
	
	
	
}




]);

使用自定义指令和服务。 *使用此tut * 遵循大多数指南 https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

1 个答案:

答案 0 :(得分:1)

我发现在multer旁边使用bodyParser会导致req.file未定义。如果您遇到问题,请务必检查。

您还需要确保name="filename"upload.single(filename)匹配。