How to upload a file using AngularJs as a traditional way

I tried this for a few days. Assuming I have the following form:

<form ng-submit="create()" class="form-horizontal" enctype="multipart/form-data"> <div class="control-group"> <label class="control-label">name : </label> <div class="controls"> <input type="text" class="input-xlarge" ng-model="message.title" /> </div> </div> <div class="control-group"> <label class="control-label">avatar : </label> <div class="controls"> <input type="file" ng-model="message.avatar" name="message[avatar]" /> </div> </div> <div class="well"> <input class="btn btn-large btn-primary" type="submit" value="建立資料" /> </div> </form> 

I use a carrier gem to handle file loading behind the scenes. My controller is as follows:

  $scope.create = function($scope.message){ var deferred = $q.defer(); $http({ method: 'POST', url: '/resources/messages', data: $.param({message: message}), headers: {'Content-Type': 'multipart/form-data'} }). success(function(data, status, headers, config){ deferred.resolve(data); }). error(function(data, status, headers, config){ deferred.reject(status); }); return deferred.promise; }; 

However, it does not work. What I intend to do is create a form and upload everything like the old one, but the examples I found, such as ng-upload, or like this post , or jquery file upload , they do not suit me. Is there any example or code sample for this purpose? Thanks.

+6
source share
1 answer

I think β€œlike the old way” is not to use Ajax, but I guess that’s not what you mean. :)

@shaunhusain fiddle is a good example of using a FormData object to handle file upload. Using this site as a link, you can use transformRequest to include a FormData object.

Keeping the base $http code, modify it to add a conversion object:

 $scope.create = function(message){ var deferred = $q.defer(); $http({ method: 'POST', url: '/resources/messages', data: message // your original form data, transformRequest: formDataObject // this sends your data to the formDataObject provider that we are defining below. headers: {'Content-Type': 'multipart/form-data'} }). success(function(data, status, headers, config){ deferred.resolve(data); }). error(function(data, status, headers, config){ deferred.reject(status); }); return deferred.promise; }; 

Create a factory that will incorporate form data management into the payload. It will iterate over your form data (including the downloaded file) and return a sender-friendly object:

 app.factory('formDataObject', function() { return function(data) { var fd = new FormData(); angular.forEach(data, function(value, key) { fd.append(key, value); }); return fd; }; }); 

I have not tested this, but it should work out of the box.

+5
source

Source: https://habr.com/ru/post/949361/


All Articles