Django文件上传不能正常工作

时间:2016-10-19 20:04:25

标签: django django-rest-framework

models.py:

>>> querty = 'Yes'
>>> querty == 'yes'  # This returns False
False
>>> querty == 'yes' or 'Yes'  # Goes to next condition since 1st is False 
'Yes'                         # Since it is non-empty string, retuns that value
                              # and 'if' treats that as True

Serializer.py

class File(models.Model):
    name = models.CharField(verbose_name="File name", max_length=200, blank=True, null=True)
    file = models.FileField(upload_to='files/%Y/%m/%d')
    upload_at = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User, related_name="uploader", blank=True, null=True)

    def __str__(self):
        return str(self.name)

views.py:

class FileSerializer(ModelSerializer):

    class Meta:
        model = File
        fields = ("id", "file", "upload_at", "user")

Anythings工作正常,但上传文件图片时损坏了!

enter image description here

我犯错误的地方?

更新

每个上传的文件都包含文件中的这一行开头:

class FileView(APIView):
    parser_classes = [FileUploadParser, MultiPartParser]
    serializer_class = FileSerializer
    permission_classes = [IsAuthenticated]
    authentication_classes = [TokenAuthentication]

    # @method_decorator(csrf_exempt)
    def post(self, request, format=None):
        serializer = FileSerializer(data=request.FILES)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=HTTP_200_OK)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

为什么呢?我怎么能删除这个?

1 个答案:

答案 0 :(得分:0)

作为documentation mentions

  

FileUploadParser适用于可以将文件作为原始数据请求上载的本机客户端。对于基于Web的上载或具有分段上传支持的本机客户端,您应该使用MultiPartParser解析器。

您应该删除解析器中的FileUploadParser或将MultiPartParser作为第一个移动。