AngularJS: Upload files using $resource (solution)

前端 未结 3 961
既然无缘
既然无缘 2020-11-27 15:35

I\'m using AngularJS to interact with a RESTful webservice, using $resource to abstract the various entities exposed. Some of this entities are ima

3条回答
  •  感动是毒
    2020-11-27 15:44

    The most minimal and least invasive solution to send $resource requests with FormData I found to be this:

    angular.module('app', [
        'ngResource'
    ])
    
    .factory('Post', function ($resource) {
        return $resource('api/post/:id', { id: "@id" }, {
            create: {
                method: "POST",
                transformRequest: angular.identity,
                headers: { 'Content-Type': undefined }
            }
        });
    })
    
    .controller('PostCtrl', function (Post) {
        var self = this;
    
        this.createPost = function (data) {
            var fd = new FormData();
            for (var key in data) {
                fd.append(key, data[key]);
            }
    
            Post.create({}, fd).$promise.then(function (res) {
                self.newPost = res;
            }).catch(function (err) {
                self.newPostError = true;
                throw err;
            });
        };
    
    });
    

提交回复
热议问题