Karim B
Karim B

Reputation: 54

Why my image is not readable after uploaded on the Django Rest Framework?

I am newbie on Django and I would like to implement a request that allow to make upload file. I wrote some code for this, but when I opened the file in local, my computer says it may be damaged. I don't understand why because the size file is the same to another when i sent with postman.

here is my code :

view.py

 def handle_uploaded_file(f):
     with open(f.name, 'wb+') as destination:
        for chunk in f.chunks():
        destination.write(chunk)


 class FileUploadView(APIView):
     parser_classes = (FileUploadParser,)

     def put(self, request, filename, format="png"):
        file_obj = request.data['file']
        handle_uploaded_file(file_obj)
        return Response(filename, status.HTTP_201_CREATED)

Upvotes: 1

Views: 494

Answers (1)

Thomas Jiang
Thomas Jiang

Reputation: 1333

Not sure if you're writing the files into the system manually but Django already has a way to handle the uploading of files - and DRF just builds on top of that. All you have to do is create a model with a FileField or any field that extends from it.

class Upload(models.Model):
    user_upload = models.FileField(upload_to='path/to/upload')

Bear in mind that the database does not store the file - it only stores the path to the file. The file is directly uploaded to the path you've specified in the field. More info about upload_to here.

To upload using DRF - all you have to do is create a serializer using ModelSerializer and use a generic API view like CreateAPIView unless you have other requirements.

Your ModelSerializer can be something like:

class UploadFileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Upload  # reference the model above
        fields = '__all__'

And in your views:

class UploadFileView(CreateAPIView):
     serializer_class = UploadFileSerializer

     def create(self, request, *args, **kwargs):
         serializer = self.get_serializer(data=request.data, files=request.FILES) # <------ note the request.FILES
         serializer.is_valid(raise_exception=True)
         self.perform_create(serializer)
         headers = self.get_success_headers(serializer.data)
         return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

That should do the trick!

Upvotes: 1

Related Questions