Image upload directive (angularJs and django rest

2019-03-15 23:58发布

问题:

I need an image upload directive, here is how my code looks like:

# Model
class transporter(models.Model):
    company_name = models.CharField(max_length=100)
    address = models.CharField(max_length=100)
    image = models.FileField(upload_to=upload_path,blank=True, null=True)

    def upload_path(self, filename):
        return 'photos/%s/%s' % (self.company_name, filename)


# Serializer
class transporterSerializer (serializers.HyperlinkedModelSerializer):
    username = serializers.Field(source='username.username')

    class Meta:
        model = transporter
        fields = ('id','company_name','address','image')

it works with only django rest framework but i get Bad request error if I post the transporter model with angularjs. I need to upload the image and set the image field with the image URL. thank you

回答1:

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
});