How to upload a file using AngularJs like the traditional way

a 夏天 提交于 2019-12-05 06:27:27

I think "like the old way" would be to not use Ajax, but I'm guessing that's not what you mean. :)

@shaunhusain's fiddle is a good example of how to use the FormData object to handle the file upload. And using this site as a reference, you can use the transformRequest to incorporate the FormData object.

Keeping your basic $http code, modify it to add the transform 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 manipulate the form data into a sendable payload. It will iterate through your form data (including uploaded 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 haven't tested this, but it should work out of the box.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!