23

我用 ImageField 创建了一个简单的模型,我想用 django-rest-framework + django-rest-swagger 创建一个 api 视图,该视图已记录并能够上传文件。

这是我得到的:

models.py

from django.utils import timezone
from django.db import models

class MyModel(models.Model):

    source = models.ImageField(upload_to=u'/photos')
    is_active = models.BooleanField(default=False)
    created_at = models.DateTimeField(default=timezone.now)

    def __unicode__(self):
        return u"photo {0}".format(self.source.url)

serializer.py

from .models import MyModel

class MyModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        fields = [
            'id',
            'source',
            'created_at',
        ]

views.py

from rest_framework import generics
from .serializer import MyModelSerializer

class MyModelView(generics.CreateAPIView):
    serializer_class = MyModelSerializer
    parser_classes = (FileUploadParser, )

    def post(self, *args, **kwargs):
        """
            Create a MyModel
            ---
            parameters:
                - name: source
                  description: file
                  required: True
                  type: file
            responseMessages:
                - code: 201
                  message: Created
        """
        return super(MyModelView, self).post(self, *args, **kwargs)

urls.py

from weddings.api.views import MyModelView

urlpatterns = patterns(
    '',
    url(r'^/api/mymodel/$', MyModelView.as_view()),
)

对我来说,这应该很简单。但是,我无法使上传工作。我总是得到这个错误响应: 在此处输入图像描述

我已经从django-rest-framework阅读了这部分文档:

If the view used with FileUploadParser is called with a filename URL keyword argument, then that argument will be used as the filename. If it is called without a filename URL keyword argument, then the client must set the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg.

但是,标头是由 django-rest-swagger 在 Request Payload 属性中传递的(来自 chrome 控制台)。

如果需要更多信息,请告诉我。

我正在使用Django==1.8.8,djangorestframework==3.3.2django-rest-swagger==0.3.4.

4

3 回答 3

8

我通过对您的代码进行了一些更改来完成这项工作。

首先,在 中models.py,将ImageField名称更改为file并使用相对路径上传文件夹。当您将文件作为二进制流上传时,它request.data在文件键 ( ) 下的字典中可用request.data.get('file'),因此最干净的选择是将其映射到具有相同名称的模型字段。

from django.utils import timezone
from django.db import models


class MyModel(models.Model):

    file = models.ImageField(upload_to=u'photos')
    is_active = models.BooleanField(default=False)
    created_at = models.DateTimeField(default=timezone.now)

    def __unicode__(self):
        return u"photo {0}".format(self.file.url)

serializer.py中,将源字段重命名为文件:

class MyModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        fields = ('id', 'file', 'created_at')

在views.py中,不要调用super,而是调用create():

from rest_framework import generics
from rest_framework.parsers import FileUploadParser

from .serializer import MyModelSerializer


class MyModelView(generics.CreateAPIView):
    serializer_class = MyModelSerializer
    parser_classes = (FileUploadParser,)

    def post(self, request, *args, **kwargs):
        """
            Create a MyModel
            ---
            parameters:
                - name: file
                  description: file
                  required: True
                  type: file
            responseMessages:
                - code: 201
                  message: Created
        """
        return self.create(request, *args, **kwargs)

我已经使用 Postman Chrome 扩展来测试这个。我已将图像上传为二进制文件,并手动设置了两个标题:

Content-Disposition: attachment; filename=upload.jpg
Content-Type: */*
于 2016-04-26T22:01:25.660 回答
6

这是我想出的最终解决方案:

from rest_framework import generics
from rest_framework.parsers import FormParser, MultiPartParser
from .serializer import MyModelSerializer

class MyModelView(generics.CreateAPIView):
    serializer_class = MyModelSerializer
    parser_classes = (FormParser, MultiPartParser)

    def post(self, *args, **kwargs):
        """
            Create a MyModel
            ---
            parameters:
                - name: source
                  description: file
                  required: True
                  type: file
            responseMessages:
                - code: 201
                  message: Created
        """
        return super(MyModelView, self).post(self, *args, **kwargs)

我所要做的就是将解析器FileUploadParser(FormParser, MultiPartParser)

于 2016-06-10T17:59:06.800 回答
3

根据我的经验,FileUploadParser使用这种请求格式的作品:

    curl -X POST -H "Content-Type:multipart/form-data" \
                 -F "file=@{filename};type=image/jpg" \
                 https://endpoint.com/upload-uri/

request.data['file']您的视图中将具有该文件。

也许如果你尝试一个Content-Type:multipart/form-data标题,你会很幸运。

于 2016-04-26T22:09:53.623 回答