Image upload directive (angularJs and django rest framework)

非 Y 不嫁゛ 提交于 2019-12-03 03:07:41

I'll share my experience with file upload using angular and drf.

Step 1:
Use a file model directive when binding your file input to an angular model. Im using the one below in several projects which does the trick for me. I got it from this blogpost by Jenny Louthan.

angular.module('appName').directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};
}]);

Used on a file input:

<form enctype="multipart/form-data">
    ...
    <input type="file" class="form-control" file-model="transporter.image">

Step 2:
Create a formData object in your controller or service which handles the post. This is can be done by first initiating a new formData object. Then looping through your angular object and setting all its attributes to that formData object.

If done in the controller this can be done like this:
(I'm using lodash for the _.each loop, but go with whatever suits you)

var fd = new FormData();
_.each($scope.transporter, function (val, key) {
    fd.append(key, data[key]);
});

Step 3:
Use angulars $http to post formData object to your url endpoint and handle the success request as you please!

$http({
    method: 'POST',
    url: '/api/url/to/endpoint',
    data: fd,
    transformRequest: angular.identity,
    headers: {
        'Content-Type': undefined
    }
}).success(function (response) {
    // Do stuff with you response
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!