Django – Upload image from b64 data to AWS

The previous post covered image file optimisation to AWS S3, using Django/Python. But a lot of frontend editors will only give us the image as b64 data, not as a regular file upload. So how do we create that from scratch?

Requirements: upload an image to S3 after it was created using a frontend editor, upload a b64 image to S3 using Django

Prerequisites: django-storages, PIL

import base64
import io

from django.core.files.base import ContentFile
from PIL import Image

from web.models import MyImageClass


def create_from_b64_data(b64_data, parent_entity):
    prefix, img_data = b64_data.split(',')
    img_data = base64.b64decode(img_data)
    buf = io.BytesIO(img_data)

    image = Image.open(buf)

    ext = image.format.lower()
    new_file = ContentFile(img_data)
    
    new_file.content_type = 'image/{}'.format(ext)
    new_file.name = format_filename(parent_entity, ext)  # customise filename as you wish

    image_data = {
        'parent_entity': parent_entity,
        'image_file': new_file,
        # ... other attributes
    }

    image = MyImageClass(**image_data)
    image.save()  # see previous post for handling in storage.py

    return image

Leave a Reply

Your email address will not be published. Required fields are marked *