简体   繁体   中英

How can i post image to Web API using angular?

This is what i have in 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:

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    
        })
    }
}])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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