Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework and File Upload

I'm trying to build file upload with DRF and jQuery. I googled and found this sample. I have some similar code on backend:

class Attachment(BaseModel):
      file = models.FileField(upload_to=get_photo_path)


class AttachmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Attachment
        fields = ('id', 'file')

class AttachmentViewSet(viewsets.ModelViewSet):
    parser_classes = (FileUploadParser, )
    serializer_class = serializers.AttachmentSerializer
    queryset = models.Attachment.objects.all()

    def pre_save(self, obj):
        obj.file = self.request.FILES.get('file')

And tried to translate Angular sample to jQuery

  var fd = new FormData()
  fd.append('file', file) // file from file-field
  var reader = new FileReader()
  $.ajax({
      url: 'http://localhost:8001/files/',
      data: fd,
      processData: false,
      contentType: false,
      type: 'POST'
  }).done(...

For some reasons I have an error on backend when try to upload a file:

detail: "FileUpload parse error - none of upload handlers can handle the stream"
like image 898
kharandziuk Avatar asked Nov 15 '15 16:11

kharandziuk


2 Answers

Actually the problem is a type of parser. I should use (FormParser, MultiPartParser, ) instead of (FileUploadParser, )

like image 61
kharandziuk Avatar answered Nov 08 '22 03:11

kharandziuk


Default Django upload handlers are:

["django.core.files.uploadhandler.MemoryFileUploadHandler", "django.core.files.uploadhandler.TemporaryFileUploadHandler"]

and there is no FILE_UPLOAD_HANDLERS parameter in the app settings file by default.

In my case I've excluded MemoryFileUploadHandler and set

FILE_UPLOAD_HANDLERS = ["django.core.files.uploadhandler.TemporaryFileUploadHandler", ]

in app settings file and it solved the problem.

like image 27
Denis Cherniatev Avatar answered Nov 08 '22 04:11

Denis Cherniatev