Skip to content

Instantly share code, notes, and snippets.

@karmadonov
Last active January 29, 2018 15:46
Show Gist options
  • Save karmadonov/3305365 to your computer and use it in GitHub Desktop.
Save karmadonov/3305365 to your computer and use it in GitHub Desktop.
Upload base64 file from POST request to Django form
import base64
import cStringIO
from django.core.files.uploadedfile import InMemoryUploadedFile
# ...
if request.POST.get('file') and request.POST.get('name'):
file = cStringIO.StringIO(base64.b64decode(request.POST['file']))
image = InMemoryUploadedFile(file,
field_name='file',
name=request.POST['name'],
content_type="image/jpeg",
size=len(file.getvalue()),
charset=None)
request.FILES[u'file'] = image
# ...
@druska
Copy link

druska commented Feb 26, 2013

You forgot to import sys :)

Copy link

ghost commented Oct 27, 2014

Your size calculation produces truncated files size=sys.getsizeof(file)
I'm guessing it's because of buffered IO.. dunno.
This works for me: size=len(file.getvalue())

@jonathancg90
Copy link

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment