upload images as raw data in django rest framework

2019-07-23 04:55发布

问题:

I am using Django-rest Framework for a project in which I am uploading the images to amazon s3 from my local system. This I am doing using the Html form which works fine.

This is the model image.

models.py

class Image(models.Model):
    image_meta = models.ForeignKey('Image_Meta',on_delete=models.CASCADE,)
    image = models.ImageField(upload_to='images-data')
    order = models.IntegerField()
    version = models.CharField(max_length=10)

But when I try to upload the image as raw data I get an error.

I want to know how can I do that. I tried to enter the location of the file in the local system for image field without any success.

What am I doing wrong here or am I missing something here?

The views.py file is below:

class ImageList(APIView):
    parser_classes = (JSONParser, )

    def get(self, request, format=None):
        images = Image.objects.all()
        serializer = ImageSerializer(images, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = ImageSerializer(data=request.data  , files=request.FILES)
        print serializer
        if serializer.is_valid():
            serializer.save()
            return Response({'received data': request.data})
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializer.py

class ImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Image
        field = ('id', 'image_path' , 'order' , 'version')

回答1:

In your api view class use

parser_classes = (FileUploadParser, MultiPartParser)

Your uploaded file be available as a file object in the request.data dictionary with the key as 'file'.

Your front end client will send the file data in the key "file".

Read more about the FileUploadParser here: http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser

code example:

class FileUploadApiView(views.APIView):


    def post(self, request, *args, **kwargs):
        form = ImageForm(request.data)
        if form.is_valid():
            image = form.save(commit=False)
        else:
            return Response(form.errors, status_code=status.HTTP_400_BAD_REQUEST)
        if request.data.get('file'):
            image_file_obj = request.data.get('file')
            # do something with file
            image_path = save_on_s3(image)
            image.image = image_path
            image.save()
            serializer = ImageSerializer(image)
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(dict(error="no image uploaded"), status_code=status.HTTP_400_BAD_REQUEST)

Here in the model I have taken the field image as a path field and not as a ImageField.