1

I am writing the backend code of a website in which there are movies and tv shows. And each film has a poster which can be used on the frontend. these posters are saved in a specific directory folder (let's say "\Posters").

What I need is an API that sends back an image (for example "Jumanji 2017.jpg") using a url like .../Poster/Jumanji_2017.jpg or .../Poster/Jumanji%202017.jpg or anything that would resemble the movie title.

Is there anyway I could do this? (preferably without making an image model)

Mohsen Amiri
  • 145
  • 14

1 Answers1

1

If you know the BASE_URL in which you will save the images as when you deploy you could save then on an external bucket (storage) then you can make something like this:

class YourModelSerialiser(serializers.ModelSerializer):

image_url = serializers.SerializerMethodField()

class Meta:
    model = YourModel
    fields = ('some_field', 'some_other_field', 'image_url')

@staticmethod
def get_image_url(obj):
    return BASE_URL + obj.image.url

but there is another approach you can use when you don't know or you don't care about the bucket(storage) url where image is saved:

class YourModelSerialiser(serializers.ModelSerializer):

image_encoded= serializers.SerializerMethodField()

class Meta:
    model = YourModel
    fields = ('some_field', 'some_other_field', 'image_encoded')

@staticmethod
def get_image_encoded(obj):
    return base64.b64encode(obj.image)

for this one you have to import base64 and then in your front end you can load image as base64 like this

<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
    AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
        9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Alt text" />

Ps. In the first example obj.image.url is the path of the image in the bucket (let it be whatever), but you need the full path to load it on the front end side.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Olsi Hoxha
  • 236
  • 2
  • 9