nicholas
nicholas

Reputation: 3

Handling file submit API response in angular

I have a form where a user uploads a file to my node server, does some stuff, and sends a JSON response.

I do not make the POST through the control, its via submitting a form. After my node code does some stuff, it sends this response succesfully.

                  res.json({ 
                    results: "TRUE",
                    file: rows,
                    column: pIndex,
                    rowCount: rows.length 
                  })

Problem, i need to access this json response in my angular app. After a user submits form, they see raw json of this response and the app redirects to my endpoint: http://localhost:8000/upload-file

What do i do to access this response in my angular app without uploading file via controller($http.post)

I have no idea, im much new to javascript. Thanks!

Upvotes: 0

Views: 1340

Answers (2)

georgeawg
georgeawg

Reputation: 48948

Upload File with AngularJS

The template

<input type=file files-input ng-model="files" /><br>
<button ng-disabled="!files[0]" ng-click="upload()">Upload</button><br>

The Upload button becomes active after the file is selected.

The files-input Directive

app.directive("filesInput", function() {
  return {
      require: "ngModel",
      link: function linkFn (scope, elem, attrs, ngModel) {
         elem.on("change", function (e) {
             ngModel.$setViewValue(elem[0].files);
         });
      }
  };
});

The directive uses the ngModelController API to bind the selected files to a scope variable.

The upload() function

var vm = $scope;
var url = "API URL";
var config = { headers: {"Content-Type": undefined} };

vm.upload = function() {

    //USE formData for Content-Type multipart/formdata        
    //var formData = new $window.FormData();
    //formData.append("file-0", vm.files[0]);

    //USE files[0] for binary upload
    $http.post(url, vm.files[0], config)
     .then(function(response) {
        vm.result = "SUCCESS";
        vm.data = response.data.data;
    }).catch(function(response) {
        vm.result = "ERROR "+response.status;
    });
};

It is important to set Content-Type: undefined so that the AngularJS framework doesn't set the content type to application/json. The XHR send method will then set the content type according the type of the given object.

It is more efficient to send the file directly, but if content type multipart/formdata with base64 encoding is desired, use the formData API to create a formData object for the XHR API to send.

The DEMO on PLNKR.

Upvotes: 1

Pop-A-Stash
Pop-A-Stash

Reputation: 6652

This is because you aren't using the Angular controller. A regular HTML form, by default will attempt to make a URL params encoded POST request to the URL defined in the action="" attribute, or, if not defined, it will POST to the current URL. The result of the post is then simply spit out into the browser window.

Angular has a directive ngSubmit that is for intercepting this default behavior so that you can handle it in a controller:

<form ng-submit="mySubmitHandler()">
...
  <input type="text" ng-model="formData.myField"/>
</form>

In your Angular controller you can now do whatever you wish. Typically you make a POST request using the $http provider:

function myController($scope) {
  $scope.formData = {
    myField: '',
  };
  $scope.mySubmitHandler = function () {
    $http.post('/someUrl', formData).then(function(response) {
      //handle the response from Node.js
    });
  };
}

The problem with this is that you are trying to upload a file. Trying to upload files with $http can be daunting. Your best bet is to use a 3rd party library to facilitate file upload in angular, such as ng-file-upload. It will come with it's own set of instructions that will allow you to handle the Node response inside of Angular.

Upvotes: 0

Related Questions