numegil
numegil

Reputation: 1926

Uploading file via base64

I'm using django-avatars to handle user profile avatars for my website. I'm currently developing a native Android app for the site, which includes the ability for users to upload an avatar. I'm passing the image data in via a get parameter encoded in base 64. In my Django view, I have

data = base64.b64decode(request.POST['data'])    
out = open("etc/test.jpeg", "wb")
out.write(data)
out.close()

to decode the image. This is working fine (test.jpeg is the file that I want it to be), but I'm having trouble tying this into django-avatars.

Looking through the source of django-avatars, the following is used to create a new avatar:

avatar = Avatar(
    user = request.user,
    primary = True,
)
image_file = request.FILES['avatar']
avatar.avatar.save(image_file.name, image_file)
avatar.save()

My question is, how can I convert my file data into the required request.FILES format, (or what's the easiest way to rewrite the save method to accept my format)

Upvotes: 3

Views: 2636

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

request.FILES elements are file-likes in a wrapper. Stick the file data in a StringIO, pass it to the django.core.files.File constructor, then pass that to save().

Upvotes: 5

Related Questions