Skip to content

Instantly share code, notes, and snippets.

@elnygren
Created October 27, 2016 19:40
Show Gist options
  • Save elnygren/d51037e7512c2051d1ce17cd3c5b092a to your computer and use it in GitHub Desktop.
Save elnygren/d51037e7512c2051d1ce17cd3c5b092a to your computer and use it in GitHub Desktop.
Populate Django request.FILES from base64 encoded file in request.POST
import base64
import io
import sys
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.exceptions import SuspiciousOperation
# WARNING: quick and dirty, should be used for reference only.
def to_file(file_from_POST):
"""base64 encoded file to Django InMemoryUploadedFile that can be placed into request.FILES.""""
# 'data:image/png;base64,<base64 encoded string>'
try:
idx = file_from_POST[:50].find(',') # comma should be pretty early on
if not idx or not file_from_POST.startswith('data:image/'):
raise Exception()
base64file = file_from_POST[idx+1:]
attributes = file_from_POST[:idx]
content_type = attributes[len('data:'):attributes.find(';')]
except Exception as e:
raise SuspiciousOperation("Invalid picture")
f = io.BytesIO(base64.b64decode(base64file))
image = InMemoryUploadedFile(f,
field_name='picture',
name='picture', # use UUIDv4 or something
content_type=content_type,
size=sys.getsizeof(f),
charset=None)
return image
def some_view(request):
f = request.POST.get('picture', None)
if f:
request.FILES['picture'] = to_file(f)
....
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment