简体   繁体   English

如何使用angular将图像发布到Web API?

[英]How can i post image to Web API using angular?

This is what i have in html modal : 这就是我在html modal中所拥有的:

<div id="name-group" class="form-group">
    <label>Upload image *</label>
    <input type="file" name="img" class="form-control" ng-model="formData.img" >
</div>`

What should I write in the factory ? 我在工厂应该写些什么?

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;
            },
  }

in controller ?? 在控制器中

In your factory I would write: 在你的工厂,我会写:

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;
    }
  }
}

And in the controller you can call the api.upload method: 在控制器中,您可以调用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    
        })
    }
}])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM