Upload Images As Raw Data In Django Rest Framework
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
Solution 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:
classFileUploadApiView(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.
Post a Comment for "Upload Images As Raw Data In Django Rest Framework"