【发布时间】:2018-01-17 18:16:14
【问题描述】:
我正在尝试将 HTML 页面中的 form-data 与图像 绑定到 Angular Controller,然后将 form-data 与图像数据一起附加,最后将数据 POST 到API。
所以我搜索并知道,遗憾的是 AngularJs 没有任何图像文件指令。
所以我得到的最终解决方案是创建一个自定义指令,将表单数据附加到图像,然后将该数据发布到服务器。
我尝试了什么:
HTML
<form role="form" enctype="multipart/form-data" name="myForm">
<input type="text" ng-model="UserName" required="required">
<input type="text" ng-model="FirstName" required="required">
<input type="file" ng-model="Image" required="required">
<button type="submit" ng-click="product()">save</button>
</form>
自定义指令:
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]);
});
});
}
};
}]);
POST 方法:
scope.product = function() {
var pro = $scope.pro;
console.log('Form Data : ' + pro);
var fd = new FormData();
angular.forEach($scope.Image, function(file) {
fd.append('file', file);
});
fd.append('pro', JSON.stringify($scope.product));
$http.post('/products/createProduct', fd, {
transformRequest: angular.identity,
headers: {
'Content-type': undefined
}
})
.then(function(data) {
$scope.ListProducts = data;
console.log($scope.ListProducts );
});
}
但问题是,控制器没有绑定任何东西,而且每次我的对象都是空的。
我什至尝试将数据记录到控制台,但没有得到任何内部数据。
我不知道我做错了什么。
请帮忙..
更新
我能够绑定数据,但是在发布图像路径和其他表单数据时,我得到了所有的空值。
angular.js:14642 可能未处理的拒绝:{"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null]," transformResponse":[null],"jsonpCallbackParam":"callback","url":"/products/createProduct","data":{"productStock":[{"price ":"","color":""}],"productThumbnail":{"0":{}}},"headers":{"Accept":"application/j儿子, text/plain, /","Content-Type":"application/json;charset=utf-8"}},"statusText":""} 错误
【问题讨论】:
-
请记住,使用 FormData API 上传图像效率不高,因为 base64 encoding 会增加 33% 的额外开销。考虑直接上传文件并使用url parameters 获取更多数据。
-
@georgeawg:我该怎么做?
-
-1 状态通常意味着CORS problem。浏览器阻止了 XHR,因为它违反了Same Origin Policy。
-
AngularJS No 'Access-Control-Allow-Origin' header 可能重复,How to enable CORS in AngularJs 可能重复,Angular HTTP: Status -1 and CORS 可能重复等 – georgeawg 5 小时前