我从AngularJS发布到一个强大的表单,但表单没有解析。我不使用express.bodyParser(),我经常理解这是一个问题。
服务器侧
...
var form = new formidable.IncomingForm();
console.log(form); //this prints
//Get access to the other fields of the request.
form.parse(req, function (err, fields, files) {
console.log("parsing.."); //this does not print
console.log(fields);
console.log(files);`
...
客户端:
...
$http({
method: 'POST',
url: '/api/ad',
data: message, // your original form data,
transformRequest: formDataObject, // this sends your data to the formDataObject provider that we are defining below. `[see this](https://stackoverflow.com/questions/17629126/how-to-upload-a-file-using-angularjs-like-the-traditional-way)`
headers: {'Content-Type': undefined}
})
.success(function(data, status, headers, config){
deferred.resolve(data); `
...
使用formData对象发布表单Angular时,我必须将内容/类型设置为undefined,如注释here中所述。可能是一个令人生畏的问题?
我已经用了几个小时试图弄明白这一点没有运气。我会非常感谢任何答案!
答案 0 :(得分:2)
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;`
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
以及以下内容将我的表单发布到我想要的网址:
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(data, uploadUrl){
var fd = new FormData();
angular.forEach(data, function(value, key) {
fd.append(key, value);
});
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(retObj){
console.log(retObj);
})
.error(function(retObj){
console.log(retObj);
});
}
}]);
在控制器的submit-function中,我现在添加:
var formData = $scope.newForm;
var uploadUrl = '/api/add';
fileUpload.uploadFileToUrl(formData, uploadUrl);
在我的html中,files-inputs获取以下标记以使用创建的文件模型:
<input type="file" file-model="newForm.image1">
我的文字输入只是像以前一样绑定:
<input type="text" ng-model="newForm.title">
希望这有助于其他人:)