Search code examples
angularjsangular-resourceangular-http

AngularJs - `$http` works But `$resource` not working - how to apply `$http` params to `$resource`


I am trying to post the image informations to back-end. I tried with $resource but not working. But when i tried with $http it seems that works. But i have added some of additiona params to $http - but i don't know how i can apply those params to $resource any one help me please?

$scope.photoData = function (photoData) {

         console.log( "photo data", photoData ); //consoles properly

        var fileData = photoData[0];
        var data = new FormData();

         var fileASHXPath =   _spPageContextInfo.webAbsoluteUrl + '/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/UploadImage/';

         //this is not working!
         $resource(fileASHXPath).save({ "photoData" : fileData }).$promise.then( function ( response ) {

            console.log( response ); //nothing works!

         })

        //this is works!

         var base = _spPageContextInfo.webAbsoluteUrl + '/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/UploadImage/';

         $http({
             url: base + 'TestImage.jpg',
             method: 'POST',
             processData: false,
             headers: { 'Content-Type': undefined },
             data: fileData
         }
                 )
                 .success(function (data) {

                     if (data.Message.toLowerCase() == 'success') {

                         console.log(data);
                     }                    

                 })
                 .error(function (msg, code) {

                     console.log('error method called');

                 });

     }

UPDATE - My NEW TRY

Still not working

$resource(base + fileName, {}, {

            post:{
                method:"POST",
                isArray:false,
                headers:{'Content-Type':'undefined'}
            }

        }).$promise.then(function ( response ) {

            console.log( "response is", response );

        })

Solution

  • try this. That is after $resource definition, call post() with form data.

    $scope.photoData = function (photoData) {
    
      console.log( "photo data", photoData ); //consoles properly
    
      var fd = new FormData();
      fd.append("photoData", photoData[0]);
    
      var fileASHXPath =   _spPageContextInfo.webAbsoluteUrl + '/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/UploadImage/';
    
      $resource(fileASHXPath, {}, {
          post: {
            method: 'POST',
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined }
          }
        }
        ).post({}, fd).$promise.then(function ( response ) {
    
          console.log( "response is", response );
    
      });
    });