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 }
      }
    });
  });
1
  • so your identityDocUpload is what holds the file? Did you have to implement listen to change with a directive? Commented Jul 20, 2017 at 7:13

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.