如何使用角度将图像发布到Web API?
问题描述:
这是我在HTML模式:如何使用角度将图像发布到Web API?
<div id="name-group" class="form-group">
<label>Upload image *</label>
<input type="file" name="img" class="form-control" ng-model="formData.img" >
</div>`
我应该在工厂里写?
var api_url = 'http://sawabapi.azurewebsites.net/api';
s.factory('api', ['$q', '$http', function ($q, $http) {
return {
upload: function (file) {
return {
post: function() {
var deferred = $q.defer();
$http.post(api_url + '/artwork/cause', file).then(function (response){
deferred.resolve(response);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
},
}
在控制器??
答
在你的工厂我会写:
s.factory('api', ['$q', '$http', function ($q, $http) {
return {
upload: function (file) {
post: function() {
var deferred = $q.defer();
$http.post(api_url+'/artwork/cause', file).then(function(response){
deferred.resolve(response);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
}
}
并在控制器,你可以调用api.upload方法:
s.controller('apiCtrl', ['$scope', 'api', function($scope, api){
$scope.upload = function(file) {
api.upload(file).then(function(response){
// Do what you want to with the response
})
}
}])