使用angular-file-model和rest_framework上传

时间:2015-03-17 13:45:32

标签: angularjs file-upload django-rest-framework

收到错误

The submitted data was not a file. Check the encoding type on the form.

我的代码如下:

型号:

class Document(models.Model):
    name = models.CharField(max_length=100, verbose_name=_('Name'))
    date = models.DateField(verbose_name=_('Date'))
    project = models.ForeignKey(Project, verbose_name=_('Project'), related_name='projects')
    type = models.CharField(max_length=50, verbose_name=_('Document Type'))
    docfile = models.FileField(upload_to='documents/%Y/%m/%d', blank=True, verbose_name=_('Document'))

    def __unicode__(self):
        return self.name

我的序列化代码:

class DocumentSaveSerializer(serializers.ModelSerializer):
    date = serializers.DateField()

    class Meta:
        model = Document
        fields = ('name', 'date', 'project', 'type', 'docfile')

我的观点:

class DocumentViewSet(WithNestedSerializerMixin, viewsets.ModelViewSet):
    serializer_class = DocumentSerializer
    queryset = Document.objects.all()

    get_object_serializer_class = DocumentSerializer
    post_serializer_class = DocumentSaveSerializer
    put_serializer_class = DocumentPutSerializer

    parser_classes = (FileUploadParser,)

    def post(self, request, *args, **kwargs):
        docfile = request.FILES['docfile']

来自前端的一些代码:

Directive: cmsApp.directive(
    'contracts',
    [
        'ContractService',
        '$rootScope',
        function (ContractService, $rootScope) {
            return {
                restrict: 'A',
                scope: {
                    contract: '=',
                    projectId: '=',
                    typeId: '=',
                    docFile: '='
                },
                templateUrl: 'main/templates/contract.html',
                link: function (scope, element, attrs) {
                scope.newContract = function(){
                    scope.contract.document.project = scope.projectId;
                    scope.contract.document.type = scope.typeId;
                    scope.contract.document.docfile = scope.docFile;
                    ContractService.createContract(scope.contract)
                    scope.contract.document = {};
                };
                }
            }
        }
    ]
)

最后是HTML:

<input type="file" file-model="docfile">

<span ng-if="DocumentName == 'Contract'" contracts contract="Contract" project-id="ProjectID" type-id="DocumentName" doc-file="docfile"></span>

没有任何想法这个代码有什么问题。安妮的建议?文件已正确加载。我通过显示名称,大小等来测试它。但是当我尝试POST时,我在本宁提到了一个错误。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

如果您是通过表单提交文件,则需要将enctype='multipart/form-data'添加到<form>标记

否则,如果您使用$http角度服务,则需要添加此标头。

headers: {'Content-Type': 'multipart/form-data'}

看起来应该是这样的:

$http({
   method: 'POST',
   url: '/your_post/url',
   data: data_with_your_file// your original form data,
   headers: {'Content-Type': 'multipart/form-data'}
}).

但是

我强烈建议您使用angular-file-upload.js以角度上传文件。非常干净,我也和DRF一起使用。