0

I want to post form data using $resource, before I was using $http as following :

upload : function(file){
          let fd = new FormData();
          fd.append('file', file);
          $http.post('http://localhost:8080/fileUpload', fd, {
              transformRequest: angular.identity,
              headers: {'Content-Type': undefined}
            })
            .success(function(){
            })
            .error(function(){
            });
        }

and now I want to use $resource instead, and this is what I tried to do but it didn't work :

upload : function(file){
          let fd = new FormData();
          fd.append('file', file);
          $resource('http://localhost:8080/fileUpload/:id',fd, {
            create: {
              method: "POST",
              transformRequest: angular.identity,
              headers: {'Content-Type': undefined}
            }
          });
        }

Edit (Solution) :

From this post AngularJS: Upload files using $resource (solution) there was two solutions the first one which was pointed out by @juandemarco was to configure the $http service but this will transform each and every request made by AngularJS, so the second one which was pointed out by @timetowonder was a better solution since I need to define this behavior only for those $resources that actually need it, so I tried as following :

in my controller :

var fd = new FormData();
      fd.append('identityDocUpload', $scope.identityDocUpload);
      fileUploadService.create({}, fd).$promise.then(function (res) {
        console.log('success');
      }).catch(function (err) {
        console.log('err');
      });

my service :

app
  .factory('fileUploadService', function ($resource) {
    return $resource('http://localhost:8080/fileUpload/:id', { id: "@id" }, {
      create: {
        method: "POST",
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
      }
    });
  });
Community
  • 1
  • 1
Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191
  • so your `identityDocUpload` is what holds the file? Did you have to implement listen to `change` with a directive? – Eric Huang Jul 20 '17 at 07:13

1 Answers1

1

As pointed out here, you CAN do it the way explained, but you'll have some browser version limitation. In the case below, he's uploading an image.

AngularJS: Upload files using $resource (solution)

Community
  • 1
  • 1
Gabriel Câmara
  • 1,249
  • 15
  • 22