我正在尝试使用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
答案 0 :(得分:1)
我发现在multer
旁边使用bodyParser
会导致req.file
未定义。如果您遇到问题,请务必检查。
您还需要确保name="filename"
和upload.single(filename)
匹配。