[Answered ]-Django S3 : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

1👍

It depends what exactly you want to do:

Display the image:

from django.http import HttpResponse
from rest_framework.decorators import api_view


@api_view(['GET'])
def get_image(request, image):
    ...
    
    data = obj['Body'].read()

    return HttpResponse(data, content_type=obj["ContentType"])

Display base64 Data URL

import base64

from django.http import HttpResponse
from rest_framework.decorators import api_view


@api_view(['GET'])
def get_image(request, image):
    ...
    
    data = obj['Body'].read()
    base64_data = base64.b64encode(data).decode("utf-8")

    return HttpResponse(f'<img src="data:{obj["ContentType"]};base64,{base64_data}">')

It looks like you’re using Django REST framework so if you want to return JSON then you’ll have to encode it using base64 for instance:

import base64

from rest_framework.decorators import api_view
from rest_framework.response import Response


@api_view(['GET'])
def get_image(request, image):
    ...
    
    data = obj['Body'].read()
    base64_data = base64.b64encode(data).decode("utf-8")

    return Response(base64_data)
👤HTF

Leave a comment