Django Rest Framework : Upload Image API

2019-09-15 04:32发布

问题:

I am trying to upload image to my django website through django rest framework api. but I am getting this error

{ "detail": "Multipart form parse error - Invalid boundary in multipart: None" }

views.py

class UploadPhotoViewSet(APIView):
    parser_classes = (parsers.MultiPartParser, parsers.FormParser)

    def get(self, request,  format=None):
        model_object = Photo.objects.all()
        serializer = PhotoSerializer(model_object, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = PhotoSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py

class PhotoSerializer(serializers.ModelSerializer):
    thumbnail = serializers.ImageField(use_url=True)
    source = serializers.ImageField(use_url=True)
    class Meta:
        model = Photo
        fields = '__all__'

model.py

class Photo(models.Model):
    type = models.CharField(max_length=100, default='photo', editable=False)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    description = models.TextField()
    category = models.CharField(max_length=255)

    def upload_thumb_dir(self, filename):
        path = '/media/{}/photos/thumbs/{}'.format(self.project.id, filename)
        return path
    thumbnail = models.ImageField(upload_to=upload_thumb_dir, default='/default/photo.png', blank=True)

    def upload_photo_dir(self, filename):
        path = '/media/{}/photos/{}'.format(self.project.id, filename)
        return path
    source = models.ImageField(upload_to=upload_photo_dir)

    def __str__(self):
        return self.title

回答1:

I wasted lot of time using curl and httpie. The best and easy way is use python requests.

I found this way to command line upload image using Django Rest Framework.

import requests
files = {'thumb': open('D:/thumb.jpg', 'rb'), 'preview': open('D:/preview.jpg', 'rb')}
r = requests.put('/path/to/your/django/rest/api', data={'key': value, 'key2': 'value2'}, files=files)
print r.status_code

If you get 201, means you done.