简体   繁体   中英

How to simplify sending (file, model) with angular and FormData

I have a form with a bunch of text fields and a file field. I'm using multer to receive the file, and that works fine. I've managed to include all necessary data in the request, but I'm not satisfied with my solution. Is there a better way to append the parameters of the form instead of manually specifying each field?

$scope.createJob = function() {
  var fd = new FormData();
  fd.append("logo", $scope.logo);
  fd.append("title", $scope.formData.title);
  fd.append("title", $scope.formData.description);
  fd.append("title", $scope.formData.hiringOrganization);
  fd.append("title", $scope.formData.jobLocation);
  fd.append("title", $scope.formData.url);
  $http.post('/api/v1/jobs', fd, {
    transformRequest: angular.identity,
    headers: {'Content-Type': undefined}
  })
  .success(function(data) {
    console.log(data);
  })
  .error(function(data) {
    console.log('Error: ' + data);
  });
};

As you can see, I'm appending each parameter of the formData object. I tried

fd.append("body", $scope.formData);
but I ended up with the string "[Object object]".

You could loop over the formData object to shorten your code:

var fd = new FormData();

for (var property in $scope.formData) {
    if ($scope.formData.hasOwnProperty(property)) {
        fd.append(property, $scope.formData[property]);
    }
}

Nope! It is not the best way. You should use javascript objects, and after that, you have to convert the object to .json file with angular.toJson() method. After that, you can post the json.

For more information please check this example: http://jsfiddle.net/aq6SY/ and see documentation: https://docs.angularjs.org/api/ng/function/angular.toJson

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM