Reputation: 789
I need to download image object from vary object storage buckets, and send that to a user through Django Rest Framework.
I have something like that:
if request.method == 'GET':
# Get object using swiftclient
conn = swiftclient.client.Connection(**credentials)
container, file = 'container_name', 'object_name'
_, data = conn.get_object(container, file)
# Send object to the browser
return Response(data, content_type="image/png")
data
variable contains bytes type.
While testing I'm receiving error:
'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
What can be solution for this problem?
Upvotes: 7
Views: 4379
Reputation: 22994
If you're looking to pass the image straight through Django Rest Framework to the user, it may be more appropriate to use an HttpResponse
.
from django.http import HttpResponse
return HttpResponse(data, content_type="image/png")
Django Rest Framework's own Response
will try and render the binary data which may cause the encoding issue you're seeing.
Upvotes: 11
Reputation: 3005
You need to import base64 and need to convert byte data into base64 encoded format, to resolve that issue.
import base64
data = base64.b64encode(data)
==== OR =====
I respect @Will Keeling answer and would like to have that in my post as well.
from django.http import HttpResponse
return HttpResponse(data, content_type="image/png")
Upvotes: 1