File upload not working with angular and webmethod

580 views Asked by At

I am basically trying to upload a file using angular and a webmethod. I took the code from this blog but it does not work. The request is successfull as seen from fiddler but the web method never gets invoked.

Am I doing something wrong?

Following is my code .

angular
  .module('loader', ['ui.router', 'ui.bootstrap', 'ui.filters'])
  .controller('loader-main', function($rootScope, $scope, WebServices) {
    $scope.uploadNewFile = function() {
      WebServices.uploadFile($scope.myfile);
    }
  }).factory('WebServices', function($rootScope, $http) {
    return {
      postFile: function(method, uploadData) {

        var uploadUrl = "myASPXPAGE.aspx/" + method;
        return $http.post(uploadUrl, uploadData, {
          transformRequest: angular.identity,
          headers: {
            'Content-Type': undefined
          }
        }).success(function(data) {
          ///Control reaches here but never hits the server method
        });
      },
      uploadFile: function(filedata) {
        var fd = new FormData();
        fd.append('file', filedata);
        return this.postFile("UploadFile", fd);
      }
    };
  }).directive('fileModel', ['$parse',
    function($parse) {
      return {
        restrict: 'A',
        link: function($scope, element, attr) {
          var model = $parse(attr.fileModel);
          var modelSetter = model.assign;
          element.bind('change', function() {
            $scope.$apply(function() {
              modelSetter($scope, element[0].files[0]);
            });
          });
        }
      }
    }
  ]);
<div class="row">
  <div class="col-xs-5">
    <div class="col-xs-4">Browse to File:</div>
    <div class="col-xs-1">
      <input type="file" id="uploadFile" class="btn btn-default" file-model="myfile" />
      <input type="button" class="btn btn-primary" value="Load File" data-ng-click="uploadNewFile()" />
    </div>
  </div>
</div>

And here is my WebMethod

    [WebMethod]
    public static string UploadFile()
    {
        System.Diagnostics.Debugger.Break();
        return "Done";
    }
1

There are 1 answers

0
Nilesh On BEST ANSWER

Figured it out. You cannot have Content-Type as multipart/form-data in webmethods. Instead created a HttpHandler to upload the file and everything works just fine.