我的文件上传存在问题。我有一个表单,在我的路由文件中将数据发送到我的控制器。发布数据时,req.file未定。我想要做的是将图像发送到我的公共/图像,然后将图像名称放入我的候选人。
这是我的表格
<div class="page-wrap text-center">
<div ng-controller = "candidatesController">
<div class = "row">
<div class=" col-md-6 col-md-offset-3">
<form class = "content-margin" ng-submit="addCandidate()" style="margin-top:30px" enctype = "multipart/form-data">
<h3 class = "formheading"> Add a new Candidate</h3>
<div class = "form-group" align = "center">
<input type = "string" class = "form-control" placeholder = "candidate name" ng-model = "formData.name" ng-style = "{'width':150 + 'px'}"></input>
</div>
<div class = "form-group" align = "center">
<input type = "string" class = "form-control" placeholder = "candidate role" ng-model = "formData.role" ng-style = "{'width':150 + 'px'}"></input>
</div>
<div class = "form-group" align = "center">
<input type = "string" class = "form-control" placeholder = "candidate email" ng-model = "formData.email" ng-style = "{'width':150 + 'px'}"></input>
</div>
<input method = "post" type="file" name="userPhoto" nd-model = "file"/>
<button type="submit" class="btn btn-primary">Add Candidate</button>
</form>
</div>
</div>
</div>
</div>
这是我的控制器
router.addPerson = function(req, res) {
console.warn(req.files);
var candidate = new CandidateModel();
candidate.name = req.body.name;
console.warn(req.body.name);
candidate.role = req.body.role;
console.warn(req.body.role);
candidate.email = req.body.email;
console.warn(req.body.email);
console.warn(candidateImage);
// Save the donation and check for errors
candidate.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Donation Added!', data: candidate });
});
}
我还没有完成文件上传代码,因为我甚至无法将文件发送过来。这是我控制器中的功能。
$scope.updateCandidate = function(){
$scope.formData.id = candidateId.getID();
$http.post('/candidates/'+ candidateId.getID(), $scope.formData)
.success(function(data){
console.log(data);
$scope.candidates = data;
$location.path('/candidates');
})
.error(function(data){
console.log('Error:' + data);
});
}
任何帮助都会很棒
答案 0 :(得分:0)
查看您的角度代码,您未将Content-Type
设置为multipart/form-data
。默认情况下$http.post()
使用application/json
return $http({
method: 'POST',
url: '/candidates/' + candidateId.getId(),
data: $scope.formData,
headers: {
'Content-Type': 'multipart/formadata'
}
})
.then((data) => {
// handle data
})
.catch((err) => {
// handle error
});