Reputation: 5953
I am trying to upload an image(part of a form) using multer on Mean Stack. However, every other data attribute is posting but I am getting undefined when it comes to image.
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);
};
}
]);
Using Custom Directive and a service. *Most guidelines are followed using this tut * https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
Upvotes: 0
Views: 814
Reputation: 8670
I found that using multer
alongside bodyParser
can cause req.file
to be undefined. Make sure to check that also if you're having issues.
You also need to make sure the name="filename"
and upload.single(filename)
matches.
Upvotes: 1